  // pages/buy/myOrder_v2/myOrder_v2.js
import Toast from "../../../dist/toast/toast";
import util from "../../../utils/util.js";
var location = require("../../../mybehaviors/location/location");

var app = getApp();
// var WxParse = require('../../../wxParse/wxParse.js');
// var qqmapsdk;

Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    noSupportDispatch: [],//不需要支持的配送方式，value为对应的dispatch_type_id
    plugin_id: "", // 应用市场用来判断请求的接口
    isDomain: false,
    clicktag: 0, // 方式提交订单多次点击
    language: "",
    //不同购买方式
    pre_order_url: "", // 预下单的请求url
    order_url: "", // 提交订单的请求url
    order_other_json: {}, // 每种类型下单的格外的请求数据
    isCartsOrder: false, // 判断是不是购物车下单类型
    options: {}, //路由参数购买方式
    _root_tag: "",
    TAG_ACTION_BUY: "-2", //直接购买
    TAG_ACTION_CART: "-1", //-1购物车结算
    _goodsId: "",
    _optionsId: "",
    _total: 1,
    _cart_ids: [],
    currentAddId: "",
    currentAddress: {},
    //O2O部分
    store_id: 0,
    storeCarts: [],
    store_info: {},
    linkinfo: {
      mobile: "",
      name: "",
    },
    selectedMode: 0,
    selected: 0,
    dispatch: [],

    deliveryTimeParams: {},//交易设置-收货地址管理-关闭地址是否需要区域
    shop_delivery_day: '',
    shop_delivery_time: "",
    shop_delivery_dayPicker: false,
    shop_delivery_timePicker: false,

    //优惠券标识
    cup_notice: true,
    isShowCoupon: false, //是否显示优惠券
    defaultAddress: {},
    realname: "", //收件人
    mobile: "",
    address: "",
    order_data: "",
    dispatch_price: 0,
    goods_price: 0,
    price: 0,
    discount_price: 0,
    deduction_price: 0,
    goodsInfo: {},
    //优惠券
    popupCouponSpecs: false,
    checkCouponList: [],
    coupon_size: 0,
    use_coupon_size: 0,
    coupons: [],
    //积分抵扣 其他抵扣
    checkDeductionList: [],
    //个人信息和修改
    myRealname: "",
    myIdcard: "",
    showMyinfo: false,
    showFrom: false,

    currentIndex: "999",
    //是否开启会员权益开关
    isOpenRight: false,
    //是否选择权益商品
    isRightChoose: false,
    //租赁商品标识
    isRent: false,
    //租期
    rentTime: [],
    //可以免租的件数
    rentFree: "",
    //免押件数
    rent_deposit_free: 0,
    //租赁协议
    agreeCon: {},
    //免租件数
    rent_free: 0,
    rentShow: false,
    tenancy: "",
    //留言
    note: {},
    //跨境
    isTaxGoods: false,
    // explain_title: "",
    // explain_content: "",
    //同意租赁协议
    agreement: false,
    agreementShow: false,
    submit_active: true,
    //是否显示支付协议
    AgreementPay: "",
    //同意支付协议
    agreementPay: false,
    //支付协议
    agreementPayShow: false,
    _show_address: false,
    // 发票
    isShowInvoice: true, //71182
    invoiceData: {
      papery_status: "",
      electron_status: "",
    },
    invoice_list: {},

    total_items: [],
    discount_amount_items: [],
    service_fee_items: [],
    //服务费
    tax_fee_items: {}, //含税
    service: {},
    isCash: "",
    goodsId: "",
    show1: false,
    isOpenTeam: false, //是否为一键开团
    isJoinTeam: false, //是否为去参团

    point: {
      lat: "",
      lng: "",
    },
    city: "",
    defaultSelfCarry: {},
    diyShow: false,
    orders_goods: {},
    diyform: {
      form_id: "",
      diyform_data_id: "",
      pre_id: "",
    },
    // 门店配送  start +++++++++++++++++++++++++++++++++++
    markers_2: [{
      // 获取返回结果，放到mks数组中
      latitude: "",
      longitude: "",
      iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
      width: 20,
      height: 25,
      callout: {
        padding: "10rpx",
        borderRadius: "5rpx",
      },
    },],
    polygons_2: [{
      points: [],
      fillColor: "#FF88887F",
      strokeColor: "#FFF",
      strokeWidth: 2,
      zIndex: 1,
    },],
    deliveryScopeShow: false,
    default_member_address: "",
    delivery: {
      longitude: "113.324520",
      latitude: "23.099994",
    },
    delivery_note: "", //门店配送说明
    delivery_area: [
      [116.403322, 39.920255]
    ], // 配送范围经纬度
    locations: [116.403322, 39.920255], //门店经纬度
    // 门店配送  end-------------------------
    integral: "",
    is_region: 0,
    activity_id: "",
    TemplateArray: [],

    orderLocationObj: {
      positioning_success: 0,
      province: "",
      city: ""
    },

    isCueCoupon: false,
    openCueCoupon: false,

    getParams_status: false, //是否已请求接口
    fromStock: "", // 是否是云库存商品

    // 话费慢充
    show_recharge_mobile: "",
    recharge_tips: "",
    recharge_mobile: "",

    // 自定义表单
    hasGoodOpenDF: false,
    // 聚合cps
    iscps: false,
    cpstype: 2,
    cpsTxt: "",
    // end
    storeSearchBtn: {}, //门店搜索插件自定义下单页按钮

    service_fee: [], //服务费、运费说明

    //上门安装 插件名：live-install
    minDate: new Date().getTime(),
    installDateShow: false,
    installDate: null, //预约时间(10位时间戳)
    installDateText: "",
    install_comment: "", //安装备注，不要超过120个字符
    location: {}, //定位信息
    showLocation: false,
    showInstallPop: false,
    default_deduction: 0, //判断积分抵扣默认是否开启

    showPage: true, //为了解决跳转的时候显示自提点的bug #64574
    delivery_amount: 0, //门店起送金额

    phone_bill_pro_goods: false, //是否话费充值pro版，根据url是否有mobile来判断

    clickMiniTemplate: false, //判断是否已经点击订阅订单
    // 供应商定位和经纬度
    // supp_adress:'',
    supp_point: {
      lng: '',
      lat: '',
      address: ''
    },
    recommend_goods: [], //满额包邮推荐商品
    // 电费充值规格组合id
    electricity_Guide: "",
    electricity: false,
    // 充值户号
    eleUser: [],
    ele_no_showAdress: false,
    // 二开页面设置插件-胜天半子#79514
    sexSelect: '1',
    showArea: false,
    // 使用微信地址，页面设置插件
    use_wechat_address: false,
    design_info: {
      cityName: "",
      countyName: "",
      detailInfo: "",
      provinceName: "",
      telNumber: "",
      userName: "",
    },

    ferightExplainPop: false,
    freightExplain: {},

    o2odeliverName: "自提点", //门店自提点自定义名称
    o2oSelfCarry: {},
    deliveryTimeShow: false,
    costSpecShow: false,
    selectCommunityShow: false,
    serviceRegionShow: false,

    //同城配送
    cityDelivery: null,
    cityDelivery_community: {},
    cityDelivery_community_id: 0,
    cityDelivery_deliveryTime: {},
    yz_subscribe_disabled: false,

    //分时预约商品
    reserve_tel_name: '',
    reserve_mobile: '',
    reserve_order: null,
    reserve_obj_text: "预约人员",
    plugin_setting: '', //插件信息 获取默认地址
    camilo_resources_coupon_type: '', //插件id：140 卡券商品 卡券商品 1直冲2卡券
    recharge_number: '',

    addressList_caller:"",  //地址组件调用着，识别是地址调用还是发票插件调用
    //油卡充值
    oil_mobile:"",
    oil_account:"",
    oil_pre_id:"",

    consigneeName: '', // 自提点提货人自定义
    consigneeMobile: '', // 自提点提货人手机号
    reserveName:'',
    reservePhone:'',
    reserveDate:'',
    delivery_information:0,
    // 地址二维码
    address_codeEnable:false,
    codeShow:false,
    hideDispatch: false,
    //地址二维码 确认信息 多次点击控制
    addressCodeClick:0,

     //联联周边游
    orderShowIdCard: 0,
    orderShowDate: 0,
    idCard: "",
    customerName: "",
    customerPhoneNumber: "",
    memo: "",
    showTravel:false,
    travelAroundTime:"", //使用时间
    travelTime:new Date().getTime(),
    travelMinDate: new Date(),
    bookingShowAddress:"",

     //自动售货机id
     machineId:"",
     is_diy_form_jump:0,// 下单跳转表单填写

     //蛋糕叔叔
     cakeCity:'', //城市信息
     cakeLat:'',
     cakeLng:'',
     cakeShipType: '', //第三方的配送方式
     cakeShipDate: '', //配送日期
     shipTimeText: '', //	配送时间
     shopDetail:'', //自提门店地址
     shopName: '', //自提门店名称
     shopId: '',
     deliveryDates:[],
     storeList: [],  //门店列表
     cakeCurrentTime:new Date().getTime(), //当前时间
     cakeEndTime:'',
     cakeMoblie:'',
     cakeText:'',
     takeDates: [],
     cakeChecked:false, //是否填写手机号
     cakeShow: false, //配送时间弹窗
     cakeTimeShow:false,
     cakeStoreShow: false,//门店列表
     canTake:0, //是否支持门店自提自提
     canSame:0, //是否支持快递配送配送
     canShip:0, // 是否支持商户自配送配送
     deliveryArr:[],
     shopCakeArr:[],
     cakeDeliveryArr:[], //获取所有的配送方式
     show_add_address:true,
     deliveryAmount:'', //运费

     yz_lease_time:{
      days: 0,
      lease_term_id: ''
    },
    // 咖啡机插件开关
    coffee_machine_open_state:false,
    coffee_goods_ids: [],
    isRentSetting:false,
    addressCheckStatus:true,
    distribution_couponData:[],
    distribution_couponSpecs:false,
    distribution_coupon_ids:[],
    address_name: "", //行政区名称
    is_custom: 0, //0 默认地图搜索，1 行政区搜索
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getStorage({
      key: "yz_basic_info",
      success: (res) => {
        let data = res.data;
        this.setData({
          reserve_obj_text: data.lang?.reserve_simple?.reserve_obj || '预约人员',
          vip_show:data.globalParameter.vip_show?data.globalParameter.vip_show:false,
          address_codeEnable: data.plugin_setting.address_code && data.plugin_setting.address_code.enable?true: false,
          hideDispatch: data.globalParameter.hide_dispatch||false,
          coffee_machine_open_state:data.globalParameter.coffee_machine_open_state === 1?true:false,
          isRentSetting:data.plugin_setting.lease_toy?data.plugin_setting.lease_toy.is_hide_price_and_deposit:false,
          order_locate:data.globalParameter && data.globalParameter.order_locate ? true : false,
          package_delivery: data.lang?.package_delivery || {}
        });
      },
    });
    this.handleQueryData(options);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });

    const value = wx.getStorageSync("integral");
    const loveName = wx.getStorageSync('yz_basic_info') ? wx.getStorageSync('yz_basic_info').love : '';
    if (value) {
      this.setData({
        integral: value,
        love_name: loveName
      });
    }
    let plugin_setting = wx.getStorageSync("yz_basic_info").plugin_setting || '';
    this.setData({
      plugin_setting
    });


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.submit_active = true;
    this.setData({
      showPage: true,
    });
    if (this.data.selected == 10) {
      // 供应商订单配送自动定位
      this._getLocation((res) => {
        let point = app.qqMapTransBMap(parseFloat(res.location.lng), parseFloat(res.location.lat));
        this.setData({
          'supp_point.lng': point.lng,
          'supp_point.lat': point.lat,
          'supp_point.address': res.address
        });
      });
    }

  },
  tolocation() {
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=suppligoodsOrde',
    });
  },
  setFreightExplainPop() {
    this.setData({
      ferightExplainPop: !this.data.ferightExplainPop
    });
  },
  getWxAdress() {
    wx.chooseAddress({
      success:  async(res) => {
        console.log(res,'chooseAddress')
        let e = res;
        this.setData({
          userAdress: `${e.provinceName} ${e.cityName} ${e.countyName}`,
          design_address: `${e.detailInfo}`,
          design_info: e
        });
        await this.checkWxAdress(e);
      }
    });
  },
  checkWxAdress(e,key=false){
    let urlStr = app.getNetAddresss("order.validate-wechat-address.index");
    let json ={
      address:{
        province:e.provinceName,
        city:e.cityName,
        district:e.countyName
      }
    }
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            addressCheckStatus:true
          })
          if(key){
            if(this.data.use_wechat_address && this.data.userAdress && this.data.design_address && (this.data.design_info.detailInfo || this.data.design_info.telNumber || this.data.design_info.userName)){
              //微信地址 开启 手动填完
              this._requestByAddress();
            }
          }else{
            this._requestByAddress();
          }
        }else{
          this.setData({
            addressCheckStatus:false
          })
          wx.showModal({
            title: '',
            content: res.msg,
            confirmText:'去修改',
          })
        }
      },
      fail: function (res) {}
    });
  },
  async handleQueryData(options) {
    //不同购买方式
    this.setData({
      options: options,
    });


    if (options.tag) {
      this.setData({
        _root_tag: options.tag,
      });
    }
    if(this.data.order_locate){
      // 二开插件 -- 下单添加定位地址（业绩区域插件和注册区域插件）
      let userLocationFlag = await this.checkAlbum("scope.userLocation");
      if (!userLocationFlag) {
        return app.tips("获取位置失败，请重新进入后授权");
      }
      if (!app.globalData.qqmapkey) {
        app._getTemplate().then((res) => {
          this.getCurrentOrderLocation();
        });
      } else {
        this.getCurrentOrderLocation();
      }
    }
    

    if (options.fromStock && options.fromStock != '') {
      this.setData({
        fromStock: options.fromStock,
      });
    }

    // 聚合cps
    if (options.iscps) {
      this.setData({
        _root_tag: "cps",
        iscps: options.iscps,
      });
    }
    if (options.mobile) {
      this.setData({
        phone_bill_pro_goods: true,
        recharge_mobile: options.mobile
      });
    }
    if (options.cpstype) {
      this.setData({
        cpstype: options.cpstype,
      });
    }
    //end

    if (options.activity_id) {
      this.setData({
        activity_id: options.activity_id,
      });
    }

    if (options.ind) {
      this.setData({
        ind: options.ind,
      });
    }

    if (options.reserve_order) {
      this.setData({
        reserve_order: JSON.parse(options.reserve_order)
      });
    }

    //是否为一键开团（拼团）
    let isOpenTeam = !app._isTextEmpty(options.level_id);
    //是否为去参团（拼团）
    let isJoinTeam = !app._isTextEmpty(options.team_id);
    this.setData({
      isOpenTeam,
      isJoinTeam,
    });

    if (options.changeSelfCarry) {
      let changeSelfCarry = JSON.parse(options.changeSelfCarry);
      if (options.ind == 12) {
        this.setData({
          o2oSelfCarry: changeSelfCarry,
        });
      } else {
        this.setData({
          defaultSelfCarry: changeSelfCarry,
        });
      }
    }



    // 设置主要参数
    this.setData({
      _goodsId: options.goodsId || "",
      _optionsId: options.optionsId || "",
      _total: options.total || 1,
    });
    //周边游参数
    if(options.tag === "tourAround") {
      this.setData({
        orderShowDate:options.orderShowDate
      })
    }
    //蛋糕叔叔
    if(options.tag === "cake") {
      //JSON.parse()
      let cakeDetail = wx.getStorageSync("cakeStoreDetail");
      if(cakeDetail) {
       let cakeStoreDetail = JSON.parse(cakeDetail);
       this.setData({
         shopId:cakeStoreDetail.shop_id,
         shopName: cakeStoreDetail.shop_name,
         shopDetail:cakeStoreDetail.address
       })
      }
      this.setData({
        cakeCity: options.city
      })
      this.handleBuy();
      //蛋糕叔叔定位的城市名称
        try {
          this._getLocation((res,e) => {
            this.setData({
              cakeLat: e.lat,
              cakeLng: e.lng,
            });
          });
          return;
        }catch (e) {
          this.getRule();
        }
   }
    if (options.cart_ids && options.cart_ids != 'undefined') {
      this.setData({
        _cart_ids: options.cart_ids ? JSON.parse(options.cart_ids) : [],
      });
    }

    // if (this.data._root_tag == this.data.TAG_ACTION_BUY || this.data._root_tag == "store") {
      if (options.store_id && options.store_id != 'undefined') {
        // 门店拓客
        this.setData({
          store_id: options.store_id,
        });
        wx.getStorage({
          key: 'storeTable',
          success: (res)=> {
            let storeTable = res.data;
            if(storeTable && storeTable.table_store == options.store_id) {
              this.setData({ storeTable });
            }
          }
        })
      }
    // }

    if (options.electricity && options.electricity == "electricity") {
      this.setData({
        electricity: true
      });
    }

    if(options.oil_account && options.oil_mobile){
      this.setData({
        oil_account:options.oil_account,
        oil_mobile:options.oil_mobile
      });
    }
    // 置换亿栈债务人id
    if(options.debtId){
      this.setData({
        debtId:options.debtId
      })
    }
    if(this.data.coffee_machine_open_state){
      this.getCoffeeMachineGoodsId();
    }
    if(options.tag == 'machine'){ //自动售货机
      this.setData({machineId:options.machineId})
    }
    console.log(this.data._root_tag,options.tag,'dwwwwdwdwdwdwd233')
    if (this.data._root_tag != "POrder" && this.data._root_tag != "store") {
      //第请求接口获取配送方式后，取默认第一个的dispatch_type_id再请求预下单接口;  挂单POrder走固定的配送方式
      this.getDispatchMethod();
    } else {
      this.handleBuy();
    }
    
  },
  // 咖啡机获取有限期
  getCoffeeMachineGoodsId(){
    if( this.data._root_tag == -1 || this.data._root_tag == -2 ){
      let arr = this.data._goodsId || this.data._cart_ids;
      let json;
      if(arr.length > 1){
        json = { goods_ids : arr.split(",") };
      }else{
        json = { goods_ids : arr }
      }
      if(this.data._root_tag == -1){
        json.create_type = 2;
      }else{
        json.create_type == 1;
      }
      let urlStr = app.getNetAddresss("plugin.coffee-machine.frontend.buyer.getCoffeeMachineGoodsId");
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data
          if (res.result == 1) {
            this.setData({
              coffeeDay : res.data.day,
              coffee_goods_ids : res.data.goods_ids
            })
          }
        },
        fail: function (res) {}
      });
    }
  },
  // 获取配送方式
  getDispatchMethod(cart_ids) {
    if (this.options.tag == "cake") {//走自己的第三方配送方式
      // this.setData({
      //   selected:'delivery'
      // })
      this.handleBuy();
      return
    };
    if (this.data._root_tag == "communityBuy") {
      // 社区团购直接设置，走配送方式接口返回为空，前端自定义，自提点不可更换
      let dispatch = [{ dispatch_type_id: 8, name: "自提点" }];
      this.setData({
        dispatch: dispatch,
        selected: 8
      });
      this.handleBuy();
      return;
    }
    let json = {
      goods_id: this.data._goodsId ? this.data._goodsId.toString() : "",
      cart_ids: this.data._cart_ids.toString() || cart_ids,
      store_id: this.data.options.store_id || this.data.options.groupStoreID,
      model: "",
    };
    if (this.data._root_tag == "store") {
      json.model = "store";
    }
    if (this.data._root_tag == "-10") {
      json.model = "packFixedPrice";
    }
    if (this.data._root_tag == "warehouse") {
      let _goods_ids = [];
      JSON.parse(this.options.goodCollection).forEach(item => {
        _goods_ids.push(item.goods_id);
      });
      json.goods_ids = JSON.stringify(_goods_ids);
    }
    if (this.data._root_tag == "agency-th") {
      let _goods_ids = [];
      JSON.parse(this.options.goods).forEach(item => {
        _goods_ids.push(item.goods_id);
      });
      json.goods_ids = JSON.stringify(_goods_ids);
      json.agency_stock_take = 1;
    }
    if (this.data._root_tag == "packagBuy" || this.data._root_tag == "giftBuy") {
      json.goods_ids = this.options.goods_ids;
    }

    if (this.data.isOpenTeam || this.data.isJoinTeam) {
      json.nonsupport =  ['15'];//不支持商城自提
    }

    let urlStr = app.getNetAddresss("memberCart.dispatch-type.index");
    if (this.data._root_tag == "exchange_code") {
      //兑换码
      urlStr =  app.getNetAddresss('plugin.exchange-code.api.dispatch.index');
      json = {
        goods_ids: this.data._goodsId ? this.data._goodsId.toString() : ""
      };

    }
    if(this.options.device_id){
      // 酒柜商品
      json.device_id = this.options.device_id;
    }

    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if(!app._isTextEmpty(this.data.debtId)){
            // 置换亿栈地址默认为快递
            this.setData({
              dispatch:[{dispatch_type_id: 1,name: "快递"}],
              selected:res.data && res.data.length > 0 ? res.data[0].dispatch_type_id : 0
            })
          }else{
            this.setData({
              dispatch: res.data,
              selected: res.data && res.data.length > 0 ? res.data[0].dispatch_type_id : 0, //默认第一
            });
            if(this.data.selected == 11){
              this.getDeliverySetting()
            }
            this.data.dispatch.forEach((items, i) => {
              if (items.dispatch_type_id == 8) {
                console.log("有自提点配送方式，请求定位获取自提点列表");
                if (this.data.ind) {
                  this.setData({
                    selected: this.data.ind,
                    selectedMode: i,
                    ind: false,
                  });
                }
              } else if (items.dispatch_type_id == 12) {
                //从门店自提点列表选择后来
                if (this.data.ind == 12 && this.data.o2oSelfCarry && this.data.o2oSelfCarry.id) {
                  this.setData({
                    selected: 12,
                    selectedMode: i
                  });
                }
              }
              if(this.data.options.get_type){
                if(this.data.options.get_type == 1 && items.dispatch_type_id == 2){
                  this.setData({
                    selected : items.dispatch_type_id,
                    selectedMode:i
                  })
                }
                if(this.data.options.get_type == 2 && items.dispatch_type_id == 3){
                  this.setData({
                    selected : items.dispatch_type_id,
                    selectedMode:i
                  })
                }
                if(this.data.options.get_type == 3 && items.dispatch_type_id == 1){
                  this.setData({
                    selected : items.dispatch_type_id,
                    selectedMode:i
                  })
                }
              }
            });
          }
          if (this.data._root_tag == "store") {
            console.log('d211111111',this.data.selectedMode)
            this._getStoreCartBuy(this.data.storeCarts);
          } else {
            this.handleBuy();
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  handleBuy(is_again) {
    // is_again判断是否重新请求数据  选择地址后是1   优惠券或者抵扣是2
    switch (this.data._root_tag) {
    case this.data.TAG_ACTION_BUY:
    case "appointment_goods":
    case "yun_sign_goods":
    case "yunqian_api":
    case "cps":
    case "starGroup":
    case "blindBox":
    case "fromExchange":
    case "newRetail":
    case "auction":
    case "zhpGroup":
    case "o2oDeposit":
      // 通常是单个商品的预下单
      if (!is_again) {
        if (this.data.options.store_id) {
          // 门店拓客  门店预约
          this._initStore("is_activity");
        } else if (this.data.options.groupStoreID && this.data.options.groupStoreID != 0 && this.data.options.groupStoreID != "undefined") {
          //门店拼团
          this._initStore();
        }
        // 只为了获取配送方式
      } else if (this.data._root_tag == "fromExchange" && is_again === "2") {
        //会员中心-兑换中心-去兑换（商城商品）
        this._getDataActionBuy(0);
        return;
      }
      this._getDataActionBuy(); // 直接购买
      break;
    case this.data.TAG_ACTION_CART: // 商城购物车结算
    case "packagBuy": // 商品套餐
    case "giftBuy": //礼包套餐
    case "-10": // 一口价
    case "communityBuy": // 社区团购
    case "purchasingCenter": // 进货中心
      this.data.isCartsOrder = true;
      // 通常是购物车的预下单
      this._getDataActionCart();
      break;
    case "store":
      this.data.isCartsOrder = true;
      if (!is_again) {
        // 门店购物车购买
        if (this.data.options.isCash == 1) {
          // 门店过期(续费 isCash =='1')商品下单
          this.getCashGood();
        } else {
          this._initStore();
        }
      } else {
        this._getDataActionStoreCart(); // 门店结算
      }
      break;
    case "rentCartBuy":
    case "rentBuy":
      if (!is_again) {
        // 租赁购物车或租赁预下单
        this.setData({
          currentIndex: "999",
          isRent: true,
        });

        this._getRentDataActionCart([], []);
        this._getRentTimeList();
        this._judgeIsRight();
      } else {
        this._rentGoodBuy();
      }
      break;
    case "yzlease":
      // 中台租赁商品
      this.setData({
        isRent:true
      })
      this._getDataActionBuy(); // 直接购买    
      break;
    case "POrder":
      //挂单商品
      this.getPendingOrder_type(); //批发区下单页类型判断,即导航栏判断
      break;
    default:
      this._getDataActionBuy(); // 直接购买
    }
  },
  reserInp(e){
    let key = e.currentTarget.dataset.key;
    let val = e.detail;
    this.setData({
      [key]:val
    })
  },
  // 处理单个商品的预下单 设置预下单链接  提交订单链接  类型额外的数据
  handleDataActionBuyUrl(json, tag) {
    if (this.data.isRent) {
      // 中台租赁商品
      if(this.data._root_tag == 'yzlease'){
        this.data.pre_order_url = app.getNetAddresss("plugin.yz-supply-lease.api.goods-buy.index");
        this.data.order_url = "plugin.yz-supply-lease.api.create.index";
        this.data.order_other_json = {
          lease_tenancy_terms_id: this.data.yz_lease_time.lease_term_id,
          nums_day:this.data.yz_lease_time.days
        };
      }else{
        if(this.options.horizon_order_id){
          this.data.order_other_json = {
            horizon_order_id:this.options.horizon_order_id
          };
        }
        // 租赁
        this.data.order_url = "plugin.lease-toy.api.order.create";
      }
    } else if (this.data.fromStock == 1 || this.data.fromStock == 2) {
      //云库存
      this.data.pre_order_url = app.getNetAddresss("plugin.agency.api.goods-buy.index");
      this.data.order_url = "plugin.agency.api.create.index";
      let agencySaleman = this.selectComponent("#agencySaleman");
      if (this.data.fromStock == 2) {
        this.data.order_other_json = {
          is_retail: true, //云库存零售传值
          salesman_uid: (agencySaleman && agencySaleman.data.self_member_id) || "" //销售员id
        };
      }
    } else if (this.data.isOpenTeam || this.data.isJoinTeam) {
      // 拼团
      this.data.order_other_json = {
        option_level_id: this.options.option_level_id, //规格层级id
      };

      let PLU = 'fight-groups';
      if(this.options.plu && this.options.plu == 'ywm') PLU = 'ywm-fight-groups';

      if (this.data.isOpenTeam) {
        this.data.order_other_json.level_id = this.options.level_id; //一键开团 拼团层级id
        this.data.pre_order_url = `plugin.${PLU}.frontend.controllers.team.pre-open-team`;
      } else if (this.data.isJoinTeam) {
        this.data.order_other_json.team_id = this.options.team_id; //一键参团 拼团层级id
        this.data.pre_order_url = `plugin.${PLU}.frontend.controllers.team.pre-join-team`;
      }

      this.data.order_url = `plugin.${PLU}.frontend.controllers.create.index`;

      if (this.options.groupStoreID && this.options.groupStoreID != 0 && this.options.groupStoreID != "undefined") {
        this.data.order_other_json.store_id = this.options.groupStoreID;
        //门店拼团
        this.data.pre_order_url = this.data.isOpenTeam ? "plugin.fight-groups.frontend.store.frontend-team.pre-open-team" : "plugin.fight-groups.frontend.store.frontend-team.pre-join-team";
        this.data.order_url = "plugin.fight-groups.frontend.store.create.index";
      }

    } else if (this.options.tag == "appointment_goods") {
      this.data.order_url = "plugin.appointment.frontend.order.create";
      if(this.data.options.exchange_code_id){ //兑换码日志id
        this.data.order_other_json = {
          exchange_code_id: this.data.options.exchange_code_id,
        };
        this.data.pre_order_url = 'plugin.exchange-code.api.goods-buy'
      }

    } else if (this.options.type == "groupBuy_open" || this.options.type == "groupBuy_join") {
      this.data.order_other_json = {
        at_id: this.options.at_id, //活动ID
        leader_id: this.options.leader_id || 0, //团长ID
      };
      delete json.option_id;
      this.data.pre_order_url = this.options.type == "groupBuy_open" ? "plugin.together-purchase.api.team.preOpenTeam" : "plugin.together-purchase.api.team.preJoinTeam";

      this.data.order_url = "plugin.together-purchase.api.create.index";
    } else if (this.options.type == "grabGroup_open" || this.options.type == "grabGroup_join") {
      //抢团
      this.data.order_other_json = {
        at_id: this.options.at_id, //活动ID
        leader_id: this.options.leader_id || 0, //团长ID
        snatch_option_id: this.data._optionsId,
      };
      json.option_id = 0;
      this.data.pre_order_url = this.options.type == "grabGroup_open" ? "plugin.snatch-regiment.api.team.preOpenTeam" : "plugin.snatch-regiment.api.team.preJoinTeam";

      this.data.order_url = "plugin.snatch-regiment.api.create.index";
    } else if (this.data._root_tag == "POrder") {
      this.data.order_other_json = {
        pending_order_type: this.data.selected, //批发订单使用类型
      };
      this.data.pre_order_url = "plugin.pending-order.frontend.goods-buy.index";

      this.data.order_url = "plugin.pending-order.frontend.create.index";
    } else if (this.data._root_tag == "o2oDeposit") {
      //门店定金团
      this.data.order_other_json = {
        store_id: this.options.store_id || 0, //门店ID
      };
      this.data.pre_order_url = "plugin.deposit-ladder.frontend.store.activity-buy";
    } else if (this.options.store_id) {
      if (this.data._root_tag == "reserve") {
        this.data.order_other_json = {
          date_id: this.options.date_id,
          store_id: this.options.store_id,
          goods_id: this.options.goodsId
        };
        if (tag == 'order') {
          this.data.order_other_json.date_id = this.options.date_id;
          this.data.order_other_json.mobile = this.data.reservePhone;
          this.data.order_other_json.realname = this.data.reserveName;
        }
        this.data.pre_order_url = "plugin.store-reserve.frontend.GoodsBuy.index";
        this.data.order_url = "plugin.store-reserve.frontend.create.index";
      } else {
        //门店拓客
        this.data.order_other_json = {
          store_id: this.options.store_id || 0, //门店ID
        };
        if (tag === "order") {
          this.data.order_other_json.mobile = this.data.linkinfo.mobile;
          this.data.order_other_json.realname = this.data.linkinfo.name;
          this.data.order_other_json.cart_ids = [];
        }

        this.data.pre_order_url = "plugin.store-cashier.frontend.store.goods-buy";
        this.data.order_url = "plugin.store-cashier.frontend.store.create";
        if(this.options.energy_machine_id){
          this.data.pre_order_url = "plugin.store-cashier.frontend.store.goods-buy";
          this.data.order_url = "plugin.energy-machine.frontend.store-create.index"
        }
        if(this.options.just_live_install){
          this.data.order_url = "plugin.live-install.frontend.store-create.index";
        }
        if(this.options.storeType == "horizon"){
          // 视界门店商品预下单
          this.data.pre_order_url = "plugin.horizon.frontend.store-goods-buy";
          this.data.order_url = "plugin.horizon.frontend.store-create";
        }
      }
      // 走门店下单
    } else if (this.data._root_tag == "blindBox") {
      this.data.order_other_json = {
        activity_id: this.data.activity_id, //活动ID
        goods_id: this.data._goodsId,
      };
      this.data.pre_order_url = "plugin.blind-box.api.buy";

      this.data.order_url = "plugin.blind-box.api.create";
    } else if (this.data._root_tag == "fromExchange") {
      //会员中心-兑换中心
      if (this.options.store_id && this.options.store_id != "undefined") {
        this.data.order_other_json.store_id = this.options.store_id;
        this.data.pre_order_url = "plugin.store-cashier.frontend.store.exchange-center";
      } else {
        this.data.pre_order_url = "coupon.exchange-center.exchange-buy";
      }
    } else if (this.options.tag == "newRetail") {
      //新零售 0-自由零售 1-成为代理商订单 2-自由发货 3-线上零售 4-进货订单 5-销售代理套餐订单
      this.data.order_other_json = {
        retail_state: Number(this.options.retailState),
        level_id: Number(this.options.NRLevelId) || 0, //等级id
        sales_id: Number(this.options.sales_id) || 0, //记录id
      };
      // if (this.options.retailState == 2) {
      //   this.data.order_other_json.goods = JSON.parse(this.options.goods) || []; // 自由发货
      // }
      this.data.pre_order_url = this.newRetailApi(this.options.retailState);

      if (Number(this.options.retailState) == 0) {
        this.data.order_url = "plugin.new-retail.frontend.create.ordinary"; // 自由发货
      } else {
        this.data.order_url = "plugin.new-retail.frontend.create.index";
      }
    } else if (this.data._root_tag == "auction") {
      //拍卖商品
      this.data.order_other_json = {
        fixed_price: this.data.options.fixed_price,
        auction_sn: this.data.options.auction_sn,
      };
      this.data.pre_order_url = "plugin.auction.api.goods-buy";

      this.data.order_url = "plugin.auction.api.order-create";
    } else if (this.data._root_tag == "zhpGroup") {
      this.data.pre_order_url = "plugin.zhp-group-lottery.frontend.goods.get-goods-Info";
      json.option_id = this.data._optionsId ? this.data._optionsId : '0';
      this.data.order_other_json = {
        activity_id: this.data.activity_id,
      };
      this.data.order_url = "plugin.zhp-group-lottery.frontend.order.index";
    } else if (this.data._root_tag == "groupWork") {
      this.data.order_other_json = {
        alliance_detail_id: this.data.options.alliance_detail_id,
        activity_option_id: this.data.options.activity_option_id
      };
      this.data.pre_order_url = "plugin.group-work.frontend.modules.order.controllers.buy.index";
      this.data.order_url = "plugin.group-work.frontend.modules.order.controllers.create.index";
    } else if (this.data._root_tag == "warehouse") {
      this.data.order_other_json = {
        goods: this.options.goodCollection
      };
      this.data.pre_order_url = "plugin.warehouse.frontend.controllers.takeDelivery.goods-buy";
      this.data.order_url = "plugin.warehouse.frontend.controllers.takeDelivery.order-create";
    }else if(!app._isTextEmpty(this.data.debtId)){
      this.data.order_other_json = {
        debtor_id: this.data.options.debtId
      };
      this.data.pre_order_url = "plugin.debt-shop.frontend.goods-buy";
      this.data.order_url = "plugin.debt-shop.frontend.create";
    }else if(this.options.tag == 'sign_buy'){
      //套餐
      this.data.order_other_json = {
        goods: JSON.parse(this.data.options.goods),
        package_id:this.data.options.package_id
      };
      this.data.pre_order_url = "plugin.sign-buy.frontend.package.pre-buy";
      this.data.order_url = "plugin.sign-buy.frontend.package.buy";
    } else if(this.options.tag == 'tourAround'){
      this.data.order_url = "plugin.travel-around.frontend.order.createOrder";
    } else if(this.options.tag == 'stock_service'){
      //存货服务
      this.data.order_other_json = {
        take_way:this.data.options.take_way,
        stock_token:this.data.options.stock_token,
        take_type:this.data.options.take_type,
        goods: `[{"goods_id":${this.data.options.goodsId},"total":${this.data.options.total},"option_id":${this.data.options.option_id}}]`
      }
      this.data.pre_order_url = "plugin.stock-service.frontend.controllers.goods-buy";
      this.data.order_url = "plugin.stock-service.frontend.controllers.order-create";

    }else if(this.data._root_tag == 'machine'){
      //自动售货机
      this.data.order_other_json.automat_machine_id = this.data.machineId;
      this.data.pre_order_url = "plugin.automat.frontend.goods-buy.index";
      this.data.order_url = "plugin.automat.frontend.create.index";
      this.setData({hideDispatch:true})
    }else if(this.options.tag === 'cake') { //蛋糕叔叔的格外参数
      this.data.order_other_json = {
        city_cake: this.data.cakeCity,
        delivery_amount:this.data.deliveryAmount,
        cake_ship_type:this.data.cakeShipType
      };
    }else if (this.options.tag == 'exchange_code'){ //兑换码
      let _goods =JSON.parse(this.data.options.goods)
      let total = 0;
      _goods.forEach(item=>{
        total+=item.total
      })
      this.data.order_other_json = {
        goods: JSON.stringify(_goods),
        total,
        exchange_code_id: this.data.options.exchange_code_id
      };
      this.data.pre_order_url = "plugin.exchange-code.api.cart.index";
      this.data.order_url = "plugin.exchange-code.api.create";
    } else if (this.options.tag == 'consignment'){ //寄售商品
      this.data.order_other_json = {
        member_voucher_id: this.data.options.VoID
      };
      this.data.pre_order_url = "plugin.consignment.frontend.controllers.order.goods-buy";
      this.data.order_url = "plugin.consignment.frontend.controllers.order.create";
    } else if (this.options.tag == "agency-th") {
      this.data.order_other_json = {
        goods: this.data.options.goods,
        agency_stock_take : 1
      };
      this.data.pre_order_url = "plugin.agency.api.stock-take.index";
      this.data.order_url = "plugin.agency.api.create-take.index";
    } else if (this.options.tag == "collection-center") {
      //数字藏品
      this.data.pre_order_url = "plugin.collection-center.frontend.controllers.order.goods-buy";
      this.data.order_url = "plugin.collection-center.frontend.controllers.order.create";
    } else if (this.options.tag == "yun_sign_goods") {
      this.data.order_url = "plugin.yun-sign.frontend.order.create";
    } else if (this.options.tag == "custom") {
      this.data.order_other_json = {
        customized_group_id: Number(this.data.options.groupId)
      };
      this.data.pre_order_url = "plugin.customized-group.frontend.controllers.goods-buy.index";
      this.data.order_url = "plugin.customized-group.frontend.controllers.create.index";
    } else if (this.options.tag == "horizon"){
      this.data.pre_order_url = "plugin.horizon.frontend.goods-buy";
      this.data.order_url = "plugin.horizon.frontend.create";
    } else if (this.options.tag == "distribution_coupon"){
      this.data.order_other_json = {
        distribution_coupon_ids: JSON.stringify(this.data.distribution_coupon_ids)
      };
      this.data.pre_order_url = "plugin.distribution-coupon.api.goods-buy";
      this.data.order_url = "plugin.distribution-coupon.api.create";
    }else if (this.options.tag == 'purchasingCenterNow'){
      this.data.pre_order_url = "plugin.gradevin-stock.frontend.controllers.goods-buy.index";
      this.data.order_url = "plugin.gradevin-stock.frontend.controllers.create.index";
    } else if (this.options.tag == 'new_auction') {
      this.data.pre_order_url = "plugin.new-auction.frontend.pick-goods-buy";
      this.data.order_url = "plugin.new-auction.frontend.pick-create";
      this.data.order_other_json = {
        new_auction_id: this.options.new_auction_id,
        new_auction_pick_num:this.options.new_auction_pick_num
      };
    }

    if (this.data.reserve_order != null) {
      this.data.order_url = "plugin.reserve-simple.frontend.order.create";
      let {
        service_id,
        obj_id,
        begin_time
      } = this.data.reserve_order;
      let customer_name = this.data.reserve_tel_name;
      let customer_tel = this.data.reserve_mobile;
      json.reserve_order = {
        service_id,
        obj_id,
        begin_time,
        customer_name,
        customer_tel
      };
      json.dispatch_type_id = 0;
    }

    if (this.options.electricity == "electricity") {
      this.data.order_other_json.account_id = this.options.account_id;
    }

    if (!this.data.pre_order_url) {
      this.data.pre_order_url = "order.goods-buy";
      if(this.data.options.exchange_code_id){
        this.data.order_url = 'plugin.yz-supply-camilo-resources.frontend.order.create.index'
        this.data.order_other_json = {
          exchange_code_id: this.data.options.exchange_code_id
        };
      }
    }

    if (!this.data.order_url) {
      if (this.data.iscps) {
        // 如果是聚合cps的商品走立即购买换这个接口
        this.data.order_url = "plugin.aggregation-cps.api.create-order";
      } else {
        this.data.order_url = "order.create";
      }
    }

    if (this.options.merchant_meeting) {
      //线下招商会商品下单，多传一个活动id
      this.data.order_other_json.merchant_meeting = this.options.merchant_meeting;
    }

    if (this.data.default_deduction != 0) {
      // 默认积分抵扣
      json.no_deduction_ids = this.data.default_deduction;
    }

    if (this.data.cityDelivery && this.data.cityDelivery.future_state == 1) {
      if (this.data.cityDelivery_deliveryTime.start_time && this.data.cityDelivery_deliveryTime.end_time) {
        json.expect_start_time = this.data.cityDelivery_deliveryTime.start_time;
        json.expect_end_time = this.data.cityDelivery_deliveryTime.end_time;
      }
    }
    if (this.data.use_wechat_address && (this.data.selected == 1 || this.data.selected == 0)) {
      // 只用于快递，并且开启了使用微信地址
      let usejson = {
        address: this.data.design_address || "",
        city: this.data.design_info.cityName,
        district: this.data.design_info.countyName,
        id: "",
        isdefault: "",
        latitude: "",
        longitude: "",
        mobile: this.data.design_info.telNumber,
        province: this.data.design_info.provinceName,
        street: "",
        uid: "",
        uniacid: "",
        username: this.data.design_info.userName,
        zipcode: "",
      };
      // 没有选择微信地址的时候，是整个adress都为空
      json.address = usejson.address?encodeURIComponent(JSON.stringify(usejson)):[];
    }

    if(this.options.name == "newBlindBox") { //新盲盒
      this.data.order_other_json = {
        new_blind_box: {
          select_goods: JSON.parse(this.options.select_goods),
          activity_id: this.options.activity_id
        }
      };
    }
    // ktv酒柜
    if(this.options.device_id){
      this.data.order_other_json.device_id = this.options.device_id;
    }
    if(this.options.cargo_road_id){
      this.data.order_other_json.cargo_road_id = this.options.cargo_road_id;
    }
    if(this.options.is_gradevin_sing){
      this.data.order_other_json.is_gradevin_sing = this.options.is_gradevin_sing;
    }
    return Object.assign(json, this.data.order_other_json);
  },
  // 处理购物车的预下单 设置预下单链接  提交订单链接  类型额外的数据
  handleDataActionCartUrl(json, tag) {
    if (this.data._root_tag == "communityBuy") {
      //社区团购
      this.data.pre_order_url = "plugin.package-deliver.frontend.cartBuy.index";
      this.data.order_other_json = {
        dispatch_type_id: 8,
        package_deliver_id: this.options.package_deliver_id,
        group_id: this.options.group_id,
      };

      this.data.order_url = "plugin.package-deliver.frontend.create.index";
    } else if (this.data._root_tag == "-10") {
      // 一口价下单
      this.data.pre_order_url = "plugin.pack-fixed-price.api.cart-buy.index";
      if (tag === "order") {
        this.data.order_other_json.cart_ids = JSON.stringify(this.data._cart_ids);
      }

      this.data.order_url = "plugin.pack-fixed-price.api.create.index";
    } else if(this.data.fromStock == 1){
      this.data.pre_order_url = "plugin.agency.api.cart-buy.index";
      this.data.order_url = "plugin.agency.api.create.index";
    }

    if (this.data._root_tag == "packagBuy") {
      let packagJson = JSON.parse(this.data.options.packagJson);
      this.data.order_other_json = {
        package_id: packagJson.package_id,
        goods: JSON.stringify(packagJson.goods_list),
      };
      this.data.pre_order_url = "plugin.goods-package.frontend.package.package-buy.index";
      this.data.order_url = "plugin.goods-package.frontend.package.create.index";
    }
    if (this.data._root_tag == "giftBuy") {
      let packagJson = JSON.parse(this.data.options.packagJson);
      this.data.order_other_json = {
        package_id: packagJson.package_id,
        goods: JSON.stringify(packagJson.goods_list),
      };
      this.data.pre_order_url = "plugin.goods-package.frontend.package.package-buy.index";
      this.data.order_url = "plugin.goods-package.frontend.package.package-create.index";
    }
    if(this.data._root_tag == 'purchasingCenter'){
      // 进货中心购物车结算
      this.data.pre_order_url = "plugin.gradevin-stock.frontend.controllers.cart-buy.index";
      this.data.order_url = "plugin.gradevin-stock.frontend.controllers.create.index";
      this.order_other_json = {
        cart_ids : JSON.parse(this.options.cart_ids)
      }
    }

    if (tag === "order" && this.data._root_tag != "-10" && this.data._root_tag != "packagBuy" && this.data._root_tag != "giftBuy") {
      // 购物车下单需要购物车id
      this.data.order_other_json.cart_ids = JSON.stringify(this.data._cart_ids);
    }

    if (!this.data.pre_order_url) {
      this.data.pre_order_url = "order.cart-buy";
    }

    if (!this.data.order_url) {
      this.data.order_url = "order.create";
      if(this.data.options.exchange_code_id){ //兑换码日志id
        this.data.order_other_json = {
          exchange_code_id: this.data.options.exchange_code_id,
        };
        this.data.pre_order_url = 'plugin.exchange-code.api.goods-buy'
      }
    }

    if (this.data.default_deduction != 0) {
      // 默认积分抵扣
      json.no_deduction_ids = this.data.default_deduction;
    }

    if (this.data.use_wechat_address && (this.data.selected == 1 || this.data.selected == 0)) {
      // 只用于快递，并且开启了使用微信地址
      let usejson = {
        address: this.data.design_address || "",
        city: this.data.design_info.cityName,
        district: this.data.design_info.countyName,
        id: "",
        isdefault: "",
        latitude: "",
        longitude: "",
        mobile: this.data.design_info.telNumber,
        province: this.data.design_info.provinceName,
        street: "",
        uid: "",
        uniacid: "",
        username: this.data.design_info.userName,
        zipcode: "",
      };
      // 没有选择微信地址的时候，是整个adress都为空
      json.address = usejson.address?encodeURIComponent(JSON.stringify(usejson)):[];
    }
    
    return Object.assign(json, this.data.order_other_json);
  },

  newRetailApi(states) {
    let state = Number(states);
    //新零售 0-自由零售 1-成为代理商订单 2-自由发货 3-线上零售 4-进货订单 5-销售代理套餐订单c
    if (state == 0) {
      return "plugin.new-retail.frontend.order.ordinaryPay";
    } else if (state == 1) {
      return "plugin.new-retail.frontend.order.purchaseRetailGoods";
    } else if (state == 2) {
      return "plugin.new-retail.frontend.order.freeSend";
    } else if (state == 3) {
      return "plugin.new-retail.frontend.order.retailCodePay";
    } else if (state == 4) {
      return "plugin.new-retail.frontend.order.purchaseStock";
    } else if (state == 5) {
      return "plugin.new-retail.frontend.order.retailCodePay";
    }
  },

  setPopShow(evt) {
    let name = evt.currentTarget.dataset.name;
    this.setData({
      [name]: !this.data[name]
    });
  },
  ///蛋糕叔叔功能代码
  //蛋糕叔叔同步手机号
  onCakeChange(event) {
    if(!this.data.address) {
      Toast('请先选择地址');
      return
    }
    if(event.detail) {
      this.setData({
        cakeMoblie: this.data.mobile,
        cakeChecked:event.detail,
      })
    } else {
      this.setData({
        cakeMoblie: '',
        cakeChecked:event.detail
      })
    }
  },
  deliveryChange(event) {
    let cakeIndex = this.data.cakeDeliveryArr.findIndex((item) => event.detail == item.dispatch_type_id);
    this.setData({
      cakeShipType: event.detail,
      selectedMode:cakeIndex
    })
    if(event.detail === 'shop') { //门店自提
      this.data.deliveryDates = this.data.shopCakeArr;
    } else {
      this.data.deliveryDates = this.data.deliveryArr;
    }
    let dates = this.data.deliveryDates;
    if(dates.length > 0) {
      let cakeCurrentTime = dates[0]?.date;
      let cakeEndTime = dates[dates.length -1]?.date;
      let startTime = new Date(cakeCurrentTime).getTime();
      let endTime =  new Date(cakeEndTime).getTime();
      this.setData({
        cakeCurrentTime: startTime,
        cakeEndTime: endTime,
        deliveryDates:this.data.deliveryDates
      });
    }
    this.handleBuy();
  },
  onCakeInput(event) {
    this.setData({
      cakeMoblie: event.detail
    })
  },
  cakePopup(event) { //配送时间弹窗
    let item = event.currentTarget.dataset.name;
    if(this.data.deliveryDates.length > 0) {
      this.setData({
        [item]: true
      })
    } else {
      Toast('没有配送日期');
    }

  },
  cakeTimePopup(event) { //配送时间弹窗
    let item = event.currentTarget.dataset.name;
    if(this.data.cakeShipDate) {
      this.setData({
        [item]: true
      })
    } else {
      Toast('请先选择配送日期');
    }

  },
  deliveryCancel(event) {
    let item = event.currentTarget.dataset.name;
    this.setData({
      [item]: false
    })
  },
  deliveryConfirm(event) {
    let time = event.detail;
    let cakeTime = this.timestampToTime(time);
    let timeData = new Date(new Date(cakeTime).toLocaleDateString()).getTime();
    let datasArr = this.data.deliveryDates;
    let deliveryObj = datasArr.find((item) => {
      let itemTime = new Date(new Date(item.date).toLocaleDateString()).getTime();//需要处理好时间才相等
      return timeData === itemTime
    });
    let deliveryArr = [];
    if(this.data.cakeShipType === 'delivery') {
      deliveryArr = deliveryObj.validate_delivery_times; //处理配送时间
      this.data.deliveryAmount = deliveryObj.delivery_amount;
      this.handleBuy();
    } else {
      deliveryArr = deliveryObj.validate_take_times; //处理配送时间
    }
    let timerData = [];
    for(let i in deliveryArr) {
      timerData.push({
        text:deliveryArr[i],
        checked: false
      })
    }
    this.setData({
      cakeShipDate:cakeTime,
      cakeShow:false,
      takeDates:timerData,
    })
  },
  cakeTimeChange(event) {
    let {text,index} = event.currentTarget.dataset;
    let takeDates = this.data.takeDates;
    for(let i in takeDates) {
      takeDates[i].checked = false
    }
    takeDates[index].checked = !takeDates[index].checked;
    this.setData({
      takeDates:takeDates,
      cakeText: text
    });
  },
  cakeTimeConfirm() {
    this.setData({
      cakeTimeShow:false,
      shipTimeText:this.data.cakeText
    })
  },
  formatDate(timestamp) {  
    if (!timestamp) return;
    let date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 注意月份是从0开始的，所以需要+1
    let day = date.getDate();  
    let hours = date.getHours();  
    let minutes = date.getMinutes();  
    let seconds = date.getSeconds();  
    
    // 使用padStart方法确保月份、日期、小时、分钟和秒都是两位数  
    month = month < 10 ? '0' + month : month;  
    day = day < 10 ? '0' + day : day;  
    hours = hours < 10 ? '0' + hours : hours;  
    minutes = minutes < 10 ? '0' + minutes : minutes;  
    seconds = seconds < 10 ? '0' + seconds : seconds;
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;  
  },
  timestampToTime(timestamp) {
    if (!timestamp) return;
    var date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let resSteam = wx.getSystemInfoSync();
    let timeicon = '';
    if(resSteam.platform == 'ios'){
      timeicon = '/'
    }else{
      timeicon = '-'
    }
    let Y = date.getFullYear() + timeicon;
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + timeicon;
    let D = this.change(date.getDate()) + " ";
    return Y + M + D;
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  setInstallDateShow() {
    this.setData({
      installDateShow: !this.data.installDateShow,
    });
  },
  gotochangeCake() {
    this.setData({
      cakeStoreShow: true,
    })
  },
  showDetail(event) {
    let detail =  event.currentTarget.dataset.item;
    let cakeDetail = JSON.stringify(detail);
    if(detail) {
      wx.setStorageSync("cakeStoreDetail", cakeDetail);
    }
    this.setData({
      cakeStoreShow: false,
      shopId:detail.shop_id,
      shopName: detail.shop_name,
      shopDetail:detail.address
    })
  },
  getRule() {
    let query = {
      city:this.data.cakeCity,
      goods_id: this.data._goodsId,
      lng:this.data.cakeLng,
      lat:this.data.cakeLat
    };
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.index.index.getStore");
    app._getNetWork({
      url: urlStr,
      data:query,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          let data = res.data;
          this.setData({
            storeList:data,
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  cakeData(orderData) {
    let cakeRule =orderData?.data?.orders[0]?.yz_supply_cake_distribution_rule?.data;  //返回值为null识别不了对象
    if (cakeRule) {
      let dispatch = [];
      let cakeShipDate = ''
      let shipTimeText = '';
      let cakeShipType ='';
      if(cakeRule.can_take === '1') {
        dispatch.push({
          dispatch_type_id: 'shop',
          name: "门店自提"
        })
      }
      if(cakeRule.can_ship === '1') {
        dispatch.push({
          dispatch_type_id: 'delivery',
          name: "商家配送"
        })
      }
      if(cakeRule.can_same === '1') {
        dispatch.push({
          dispatch_type_id: 'same',
          name: "快递"
        })
        cakeShipDate = false;
        shipTimeText = cakeRule.delivery_text;
        this.setData({
          cakeShipDate: cakeShipDate,
        })
      }
      this.setData({
        cakeDeliveryArr:dispatch
      })
      //默认第一次蛋糕叔叔是没有类型的，需要有一个默认配送方式类型
      this.data.cakeDeliveryArr.forEach((item,index) => { //获取对应的配送方式
        if(index === this.data.selectedMode) {
          cakeShipType = item.dispatch_type_id
        }
      })
      let dates = [];
      if(cakeShipType === 'delivery' ) {
          dates = cakeRule.validate_delivery_dates; //处理配送时间
          this.setData({
            deliveryArr:dates,
            deliveryAmount:dates[0]?.delivery_amount
          })
      } else {
        dates = cakeRule.validate_take_dates; //处理配送时间
      }
      this.setData({
        shopCakeArr:cakeRule.validate_take_dates
      })
      let cakeCurrentTime = dates[0]?.date;
      let cakeEndTime = dates[dates.length -1]?.date;
      let startTime = new Date(cakeCurrentTime).getTime();
      let endTime =  new Date(cakeEndTime).getTime();
      this.setData({
        deliveryDates: dates,
        canSame: cakeRule.can_same,
        canTake: cakeRule.can_take,
        canShip: cakeRule.can_ship,
        cakeShipType: cakeShipType,
        shipTimeText: shipTimeText,
        cakeCurrentTime: startTime,
        cakeEndTime: endTime,
      });
    }

  },
  /**/
  bindInstallDateChange(e) {
    this.setInstallDateShow();
    let val = e.detail;
    this.setData({
      installDate: parseInt(val / 1000),
      installDateText: util.formatTime(new Date(val)),
    });
  },
  // 门店配送-查看配送范围
  showDeliveryMap() {
    this.setData({
      deliveryScopeShow: true,
    });
  },
  showLocationPop() {
    this.setData({
      showInstallPop: !this.data.showInstallPop,
    });
  },
  deliveryScopeShowClose() {
    this.setData({
      deliveryScopeShow: false,
    });
  },
  confirmLocation(e) {
    this.setData({
      "location.latitude": e.detail.lat,
      "location.longitude": e.detail.lng,
      "location.address": e.detail.address,
    });
    this.showLocationPop();
  },
  _checkTaxGoods(data) {
    if (data && data.status) {
      //显示个人信息
      this.setData({
        showMyinfo: data.status,
      });
      this.data.isTaxGoods = true;
    } else {
      this.data.isTaxGoods = false;
      this.setData({
        showMyinfo: false,
      });
      //隐藏个人信息
    }
  },
  _getMemberInfo(data) {
    this.setData({
      myRealname: data.realname,
      myIdcard: data.idcard,
    });
  },
  // _getExplain(data) {
  //   this.data.explain_title = data.explain_title;
  //   this.data.explain_content = data.explain_content;
  // },
  //保税真实信息添加
  alertMyInfo() {
    this.setData({
      showFrom: true,
    });
  },
  confirmFrom(e) {
    this.setData({
      myRealname:e.detail.name,
      myIdcard:e.detail.card,
      showFrom: e.detail.status,
    });
  },
  //更换自提点
  gotochangeSelfCarry() {
    let that = this;
    //保存自提点信息到本地，任务编号: 35632
    let _memberInfoes = {
      distributionUserName: this.data.linkinfo.name ? this.data.linkinfo.name : "",
      distributionUserMobile: this.data.linkinfo.mobile ? this.data.linkinfo.mobile : "",
    };
    try {
      wx.setStorageSync("selfCarryInfo", JSON.stringify(_memberInfoes));
    } catch (e) {
      console.log(e);
    }

    let url =
      "/packageC/selfCarry/selfCarry_info/selfCarry_info?tag=" +
      that.data.options.tag +
      "&goodsId=" +
      that.data.options.goodsId +
      "&optionsId=" +
      that.data.options.optionsId +
      "&total=" +
      that.data.options.total +
      "&goods=" +
      JSON.stringify(this._assembleGoods()) +
      "&ind=" +
      that.data.selected;

    if(that.data.options.cart_ids){
      url = url + "&cart_ids=" + that.data.options.cart_ids;
    }

    if (that.data.isOpenTeam) {
      url = url + "&level_id=" + that.options.level_id + "&option_level_id=" + that.options.option_level_id;
      if(this.options.plu && this.options.plu == 'ywm') url = url + "&plu=ywm"
    } else if (that.data.isJoinTeam) {
      url = url + "&team_id=" + that.options.team_id + "&option_level_id=" + that.options.option_level_id;
      if(this.options.plu && this.options.plu == 'ywm') url = url + "&plu=ywm"
    }

    if (this.data._root_tag == "warehouse") {
      // 圈仓
      url = url + "&goodCollection=" + this.options.goodCollection;
    }

    if (this.options.store_id) {
      // 门店id
      url = url + "&store_id=" + this.options.store_id;
    }

    if (this.options.groupStoreID && Number(this.options.groupStoreID)>0) {
      // 门店id
      url = url + "&groupStoreID=" + this.options.groupStoreID;
    }
    if(this.options.exchangeData) {
      url = url + "&exchangeData=" + this.options.exchangeData;
    }

    wx.redirectTo({
      url: url,
    });
  },

  // 切换配送方式
  setDispatch(e) {
    let title = e.detail.title;
    this.setData({
      yz_subscribe_disabled:false
    })
    if(this.options.tag === "cake") {  //走第三方的配送方式
      let cakeShipType = '';
      this.data.dispatch.forEach((items) => {
        if (items.name == title) {
          cakeShipType = items.dispatch_type_id;
        }
      });
      this.setData({
        cakeShipDate:'',
        shipTimeText:'',
        cakeShipType:cakeShipType
      })
    };
    this.data.dispatch.forEach((items) => {
      if (items.name == title) {
        this.setData({
          selected: items.dispatch_type_id,
          selectedMode: e.detail.index,
        });
      }
    });
    if (this.data.selected == 10) {
      // 供应商订单配送自动定位
      this._getLocation((res) => {
        let point = app.qqMapTransBMap(parseFloat(res.location.lng), parseFloat(res.location.lat));
        this.setData({
          'supp_point.lng': point.lng,
          'supp_point.lat': point.lat,
          'supp_point.address': res.address
        });
      });
    }
    if (this.data.selected == "11") {
      //selected = 11 同城配送
      this.getDeliverySetting();
    } else {
      this._requestByAddress();
    }

  },

  getDeliverySetting() {
    if (this.data.cityDelivery != null) {
      this.data.order_data.forEach((item) => {
        // *1 只是为了转数字类型
        if ((this.data.cityDelivery.min_amount * 1) > (item.goods_price * 1)) {
          this.setData({
            yz_subscribe_disabled:true //商品价格不够最低配送，按钮灰色不能提交
          })
        }
      });
      this._requestByAddress();
      return;
    }
    let urlStr = app.getNetAddresss("plugin.city-delivery.frontend.order.getDeliverySetting");
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let changeData = {};
          changeData.cityDelivery = res.data;

          if (res.data.fence_setting) {
            changeData["markers_2[0].longitude"] = res.data.fence_setting.store_longitude;
            changeData["markers_2[0].latitude"] = res.data.fence_setting.store_latitude;
            changeData["delivery.longitude"] = res.data.fence_setting.store_longitude;
            changeData["delivery.latitude"] = res.data.fence_setting.store_latitude;
            if (res.data.fence_setting.delivery_area) {
              changeData["polygons_2[0].points"] = res.data.fence_setting.delivery_area.map((item) => {
                let o = {};
                o.longitude = item[0];
                o.latitude = item[1];
                return o;
              });
            }
          }
          changeData.need_lat = 1;

          if(this.data.order_data){
            this.data.order_data.forEach((item) => {
              // *1 只是为了转数字类型
              if ((res.data.min_amount * 1) > (item.goods_price * 1)) {
                this.setData({
                  yz_subscribe_disabled:true //商品价格不够最低配送，按钮灰色不能提交
                })
              }
            });
          }
          this.setData(changeData);
          this.selectComponent(`.deliveryTime`).setListData(res.data.time_setting, res.data.default_choose);
          if (!res.data.default_choose) {
            this._requestByAddress();
          }
        }
      }
    });
  },

  //直接购买
  _getDataActionBuy(is_exchange) {
    let that = this;
    let _json = {
      goods_id: this.data._goodsId,
      total: this.data._total,
      option_id: this.data._optionsId || '0',
      member_coupon_ids: this._assembleCoupons(),
      orders: JSON.stringify(this._assembleDeduction()),
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress)), //encodeURIComponent为了解决地址#号问题
      dispatch_type_id: this.data.selected,
      mark: this.data.options.mark ? this.data.options.mark : 0,
      first_default:  this.first_default||''//是否首次请求，之后的请求都要回传这个参数。没有传这个参数的订单全部按默认首次请求处理
    };
    // 中台租赁商品
    if(this.data._root_tag == 'yzlease' && this.data.yz_lease_time.days){
      _json.lease_tenancy_terms_id = this.data.yz_lease_time.lease_term_id;
      _json.nums_day = this.data.yz_lease_time.days;
      // _json.total = this.data.yz_lease_time.days;
      console.log(_json)
    }
    //自提点开启
    if (this.data.selected == 8) {
      _json.package_deliver_id = this.data.defaultSelfCarry.id;
    }
    if (this.data.selected == 12) {
      // 门店自提点
      _json.package_deliver_id = this.data.o2oSelfCarry.id;
    }

    if (this.data._root_tag == "fromExchange") {
      //兑换中心商品
      _json.data = JSON.parse(this.data.options.exchangeData);
      _json.is_exchange = is_exchange == 0 ? 0 : 1;
    }

    if (this.options.tag == "newRetail" && this.options.retailState == 2) {
      _json.goods = JSON.parse(this.options.goods) || []; // 自由发货
    }
    console.log('ddddddddddd',_json)
    if(this.options.energy_machine_id){
      _json.energy_machine_id = this.options.energy_machine_id;
    }
    if(this.options.tag == 'new_auction'){
      _json.new_auction_id = this.options.new_auction_id;
      _json.new_auction_pick_num = this.options.new_auction_pick_num;
    }
    _json = this.handleDataActionBuyUrl(_json);
    let urlStr = app.getNetAddresss(this.data.pre_order_url);
    wx.showLoading({
      title: "加载中",
      icon: "none",
      duration: 1500,
    });
    if (this.data.clicktag == 0) {
      this.setData({
        clicktag: 1,
      });
      app._postNetWork({
        url: urlStr,
        data: _json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.options.tag == "reserve") {
              // 门店预约商品
              if (res.data.reserve_date) {
                this.setData({
                  reserveDate: res.data.reserve_date.date
                });
              }
              if (res.data.reserve_deduction) {
                this.setData({
                  reserve_deduction: res.data.reserve_deduction
                });
              }
              if (res.data.reserve_deduction_love) {
                this.setData({
                  reserve_deduction_love: res.data.reserve_deduction_love
                });
              }
            }
            if (that.options.tag == "tourAround") {
              this.setData({
                orderShowIdCard: res.data.orders[0]?.travel_around_order.orderShowIdCard,
                bookingShowAddress: res.data.orders[0]?.travel_around_order.bookingShowAddress
              });
            }
            if (that.options.tag == "cake") {  //蛋糕叔叔
              let res = resdata.data;
              this.cakeData(res);
            }
            if (that.options.type == "groupBuy_open" || that.options.type == "groupBuy_join") {
              that.setData({
                isGetAgreementPay: true,
                AgreementPay: that.data.goodsInfo.together_purchase_agreement ? that.data.goodsInfo.together_purchase_agreement : "",
              });
            }

            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
              diyShow: false,
            });
            that._setViewData(res.data); //设置界面
            if (this.data._root_tag == "fromExchange") {
              //兑换中心
              that.defaultSelectCoupon(res.data.discount.member_coupons); //设置默认优惠券信息
            } else if (res.data.discount) {
              that._initCoupon(res.data.discount); //设置优惠券信息
            }
            if(this.data.codeShow){
              // 地址确认弹窗打开后走下单 走这个方法 feat#1565
              this.submitBtnPost()
            }
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg,
              success: (resData)=> {
                if (resData.confirm) {
                  if(res.data.address_error == '404'){
                    wx.navigateTo({
                      url: '/packageD/member/addressList/addressList',
                    })
                    return
                  }
                  try {
                    const orderErrReturnUrl = wx.getStorageSync('orderErrReturnUrl')
                    if (orderErrReturnUrl) {
                      wx.redirectTo({
                        url: orderErrReturnUrl
                      });
                    } else{
                      if(this.data._root_tag != 'yzlease'){
                        wx.navigateBack({
                          delta: 1
                        });
                      }
                      
                    }
                  } catch (e) {
                    if(this.data._root_tag != 'yzlease'){
                      wx.navigateBack({
                        delta: 1
                      });
                    }
                  }
                } else if (resData.cancel) {
                  wx.navigateBack({
                    delta: 1
                  });
                }
              },
            });
          }
          setTimeout(() => {
            that.setData({
              cup_notice: true,
              clicktag: 0,
            });
            wx.hideLoading();
          }, 1000);
        },
        fail: (res) => {
          console.log(res);
        },
      });
    }
  },
  //购物车结算
  _getDataActionCart() {
    let that = this;
    let _json = {
      cart_ids: this.data._cart_ids.toString(),
      member_coupon_ids: this._assembleCoupons(),
      orders: JSON.stringify(this._assembleDeduction()),
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress)),
      dispatch_type_id: this.data.selected,
    };
    if (this.data.selected == 8) {
      _json.package_deliver_id = this.data.defaultSelfCarry.id;
    }
    if (this.data.selected == 12) {
      // 门店自提点
      _json.package_deliver_id = this.data.o2oSelfCarry.id;
    }
    this.data.order_other_json = {};
    _json = this.handleDataActionCartUrl(_json);
    let urlStr = app.getNetAddresss(this.data.pre_order_url);
    app._getNetWork({
      url: urlStr,
      data: _json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
            cup_notice: true,
            diyShow: false,
          });

          that._initCoupon(res.data.discount); //设置优惠券信息
          that._setViewData(res.data); //设置界面
          if(this.data.codeShow){
            // 地址确认弹窗打开后走下单 走这个方法 feat#1565
            this.submitBtnPost()
          }
        } else {
          that.setData({
            cup_notice: true,
          });
          Toast(res.msg);
          wx.showModal({
            title: "提示",
            content: res.msg,
            showCancel: false,
            success(res) {
              wx.navigateBack({
                delta: 1,
              });
            },
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  // 获取门店数据
  _initStore(str) {
    var that = this;
    let store_id = this.options.groupStoreID && this.options.groupStoreID != "undefined" ? this.options.groupStoreID : this.data.store_id;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-info-by-store-id");
    urlStr += "&store_id=" + store_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            store_info: res.data,
            store_carry: res.data.store_carry,
          });
          if (str !== "is_activity" && !that.options.groupStoreID) {
            that._getDataActionStoreCart();
          }
          // 门店配送规则数据
          if ((res.data.store_delivery && res.data.store_delivery.delivery_status) || res.data.need_lat == 1) {

            that.setData({
              need_lat: res.data.need_lat, //跑腿配送插件，res.data.need_lat为1的时候，需要设置经纬度
              delivery_status: res.data.store_delivery.delivery_status,
              delivery_note: res.data.store_delivery ? res.data.store_delivery.delivery_note : "",
              delivery_amount: res.data.store_delivery ? res.data.store_delivery.delivery_amount : 0,
            });

            let delivery_area = res.data.store_delivery && res.data.store_delivery.delivery_area != "" ? res.data.store_delivery.delivery_area : [];
            let locations = res.data.store_delivery ? res.data.store_delivery.locations : {};
            let arr_delivery_area = [];
            delivery_area.forEach((item, index) => {
              arr_delivery_area.push([Number(item.R), Number(item.Q)]);
            });
            that.setData({
              delivery_area: arr_delivery_area,
              locations: [Number(locations.longitude).toFixed(6), Number(locations.latitude).toFixed(6)],
              is_custom: res.data.store_delivery ? res.data.store_delivery.is_custom : 0,
              address_name: res.data.store_delivery ? res.data.store_delivery.address_name : ""
            });
            if (that.data.locations && that.data.locations.length > 0) {
              that.setData({
                "markers_2[0].longitude": that.data.locations[0],
                "markers_2[0].latitude": that.data.locations[1],
                "delivery.longitude": that.data.locations[0],
                "delivery.latitude": that.data.locations[1],
              });
            }
            if (that.data.delivery_area && that.data.delivery_area.length > 0) {
              let points = [];
              for (let i = 0; i < that.data.delivery_area.length; i++) {
                points.push({
                  longitude: that.data.delivery_area[i][0],
                  latitude: that.data.delivery_area[i][1],
                });
              }
              that.setData({
                "polygons_2[0].points": points,
              });
            }
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //门店过期商品下单
  getCashGood() {
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.enter.getSetGoodsId");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goods_id: res.data.goods_id,
          });
          if (!res.data.store) {
            that.setData({
              _root_tag: "-2",
              _goodsId: res.data.goods_id,
              store_id: 0,
            });
            that._getDataActionBuy();
          } else {
            that.setData({
              _root_tag: "store",
              store_info: res.data.store,
              store_id: res.data.store.id || res.data.store.store_id,
            });
            that._getDataActionStoreCart();
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //门店购物车商品
  _getDataActionStoreCart() {
    if (!this.data.store_id) {
      return;
    }
    if (this.data.storeCarts.length > 0) {
      // 已经有storeCarts就不重复请求了
      this.setData({
        cup_notice: true,
      });
      this._getStoreCartBuy(this.data.storeCarts);
      return;
    }
    if (this.data._cart_ids && this.data._cart_ids.length > 0) {
      this.data.storeCarts = this.data._cart_ids;
      this.getDispatchMethod(this.data.storeCarts.toString());
      return;
    }

    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.index");
    if(this.options.just_live_install) {
      urlStr += "&just_live_install=1";
    }
    urlStr += "&store_id=" + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let storeCarts = [];
          res.data.forEach((item) => {
            if(item.is_failure == 0){
              storeCarts.push(item.id);
            }
          });
          that.setData({
            cup_notice: true,
            storeCarts: storeCarts,
          });
          this.getDispatchMethod(that.data.storeCarts.toString());
        } else {
          that.setData({
            cup_notice: true,
          });
          wx.showToast({
            icon: "none",
            title: "无商品",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //门店结算
  _getStoreCartBuy(cart_ids) {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.cart-buy");
    let json = {
      // cart_ids: cart_ids,
      store_id: this.data.store_id,
      dispatch_type_id: this.data.selected,
      member_coupon_ids: this._assembleCoupons(),
      orders: JSON.stringify(this._assembleDeduction()),
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress))
    };
    


    if(this.options.just_live_install) {
      urlStr = app.getNetAddresss('plugin.live-install.frontend.store-cart-buy.index');
      json.dispatch_type_id = 1;
      json.live_install_order_replace_uid = this.options.live_install_order_replace_uid;
      this.setData({
        live_install_order_replace_uid: this.options.live_install_order_replace_uid
      })
    }
    urlStr += "&cart_ids=" + cart_ids;
    if (this.data.selected == 8) {
      json.package_deliver_id = this.data.defaultSelfCarry.id;
    }
    if (this.data.selected == 12) {
      // 门店自提点
      json.package_deliver_id = this.data.o2oSelfCarry.id;
    }

    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodsInfo: res.data,
          });
          that._initCoupon(res.data.discount); //设置优惠券信息
          that._setViewData(res.data, cart_ids); //设置界面
          if(this.data.codeShow){
            // 地址确认弹窗打开后走下单 走这个方法 feat#1565
            this.submitBtnPost()
          }
        } else {
          that.setData({
            none_loc: false,
          });
          if (that.data.showAddressList) {
            return;
          }
          if (res.msg === "请完善地址经纬度信息") {
            // 门店配送提示不能返回上一页 #62588
            wx.showModal({
              title: '提示',
              content: "请完善收件人的地址经纬度信息",
              confirmText: '确认',
              showCancel: false,
              success(res) {
                if (res.confirm) {}
              }
            });
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
              confirmText: '确认',
              showCancel: false,
              success(response) {
                if (response.confirm) {
                  if (res.msg.indexOf('配送范围') < 0) {
                    wx.navigateBack({
                      delta: 1,
                    });
                  }
                }
              }
            });
            // Toast(res.msg);
            // setTimeout(() => {
            //   wx.navigateBack({
            //     delta: 1,
            //   });
            // }, 4000);
          }
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  //租赁购物车结算
  _getRentDataActionCart(right, rent) {
    if (this.data._root_tag == "rentCartBuy") {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.lease-toy.api.order.cart-buy");
      urlStr += "&lease_rights=" + right;
      urlStr += "&lease_term=" + rent;
      urlStr += "&cart_ids=" + this.data._cart_ids.toString();
      urlStr += "&member_coupon_ids=" + this._assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
      urlStr += "&address=" + encodeURIComponent(JSON.stringify(this.data.currentAddress));
      urlStr += "&dispatch_type_id=" + this.data.selected;
      //自提点开启
      if (this.data.selected == 8) {
        urlStr += "&package_deliver_id=" + this.data.defaultSelfCarry.id;
      }
      if (this.data.selected == 12) {
        // 门店自提点提货
        urlStr += "&package_deliver_id=" + this.data.o2oSelfCarry.id;
      }
      urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
            });

            that._initCoupon(res.data.discount); //设置优惠券信息
            that._setViewData(res.data); //设置界面
            if(this.data.codeShow){
              // 地址确认弹窗打开后走下单 走这个方法 feat#1565
              this.submitBtnPost()
            }
          } else {
            that.setData({
              cup_notice: true,
            });
            Toast(res.msg);
          }
        },
        fail: (res) => {
          console.log(res);
        },
      });
    } else if (this.data._root_tag == "rentBuy") {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.lease-toy.api.order.goods-buy");
      urlStr += "&lease_rights=" + right;
      urlStr += "&lease_term=" + rent;
      urlStr += "&goods_id=" + this.data._goodsId;
      urlStr += "&total=" + this.data._total;
      urlStr += "&option_id=" + this.data._optionsId;
      urlStr += "&member_coupon_ids=" + this._assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());
      urlStr += "&address=" + encodeURIComponent(JSON.stringify(this.data.currentAddress));
      urlStr += "&dispatch_type_id=" + this.data.selected;
      if (this.options.horizon_order_id && this.data.options.tag == "rentBuy"){
        urlStr += "&horizon_order_id=" + this.options.horizon_order_id;
      }
      //自提点开启
      if (this.data.selected == 8) {
        urlStr += "&package_deliver_id=" + this.data.defaultSelfCarry.id;
      }
      if (this.data.selected == 12) {
        // 门店自提点提货
        urlStr += "&package_deliver_id=" + this.data.o2oSelfCarry.id;
      }
      urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        app._getNetWork({
          url: urlStr,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              that.setData({
                goodsInfo: res.data,
                cup_notice: true,
              });

              that._initCoupon(res.data.discount); //设置优惠券信息
              that._setViewData(res.data); //设置界面
              if(that.data.codeShow){
                // 地址确认弹窗打开后走下单 走这个方法 feat#1565
                that.submitBtnPost()
              }
            } else {
              Toast(res.msg);
            }
            setTimeout(() => {
              that.setData({
                clicktag: 0,
              });
            }, 1000);
          },
          fail: (res) => {
            console.log(res);
          },
        });
      }
    }
  },
  //获取租期列表
  _getRentTimeList() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.lease-toy.api.lease-term.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res.data,'plugin.lease-toy.api.lease-term.index')
          that.setData({
            rentTime: res.data.list,
            rentFree: res.data.level.rent_free,
            agreeCon: res.data.lease_toy_set,
            rent_deposit_free: res.data.level.deposit_free,
            rent_free: res.data.level.rent_free,
          });
          // let article_1 = that.data.agreeCon.lease_toy_pact ? that.data.agreeCon.lease_toy_pact : '';
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          // WxParse.wxParse('article_1', 'html', article_1, that);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  _rentGoodBuy() {
    if (this.data.isOpenRight) {
      let rentTimeRight = "";
      const value = wx.getStorageSync("rentTimeRight");
      if (value) {
        rentTimeRight = value;
      }
      this._getRentDataActionCart(rentTimeRight, []);
    } else {
      if (this.data.currentIndex == "999") {
        let rentTimeSelf = "";
        const value = wx.getStorageSync("rentTimeSelf");
        if (value) {
          rentTimeSelf = value;
        }
        if (!app._isTextEmpty(rentTimeSelf)) {
          this._getRentDataActionCart([], rentTimeSelf);
        } else {
          this._getRentDataActionCart([], []);
        }
      } else {
        let rentTimeChoose = "";
        const value = wx.getStorageSync("rentTimeChoose");
        if (value) {
          rentTimeChoose = value;
        }
        if (!app._isTextEmpty(rentTimeChoose)) {
          this._getRentDataActionCart([], rentTimeChoose);
        }
      }
    }
  },

  // 挂单
  getPendingOrder_type() {
    //获取批发区下单页类型判断
    //挂单不适合配送方式
    let urlStr = app.getNetAddresss("plugin.pending-order.frontend.wholesale-area.pending-order-type");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 1,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.status == 0) {
            let dispatch = [{
              name: "零售",
              dispatch_type_id: 0,
            },
            {
              name: "自用",
              dispatch_type_id: 1,
            },
            ];
            that.setData({
              dispatch: dispatch,
              selected: 0,
            });
          } else {
            let dispatch = [{
              name: "自用",
              dispatch_type_id: 1,
            },];
            that.setData({
              dispatch: dispatch,
              selected: 1,
            });
          }
          that._getDataActionBuy();
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  //显示地址pop
  showAddress(e) {
    //获取收货地址
    this.setData({
      showAddressList: true,
      addressList_caller:"express"
    });
    if(this.data.showAddressList){
      let address = this.selectComponent('#yz_showAddressShop');
      address.setData({
        add_address : this.data.show_add_address
      })
    }
    if(e.currentTarget.dataset.code){
      this.setData({
        codeShow:false
      })
    }
  },
  invoiceShowAddressFun(){
    this.setData({
      showAddressList: true,
      addressList_caller:"invoice"
    });
  },
  onPeripheryChange(event) {  //监听周边游的输入框输入
    let itemName = event.currentTarget.dataset.partname;
    this.setData({
      [itemName]: event.detail
    })
  },
  travelUp() {
    this.setData({
      showTravel:true
    })
  },
  travelConfirm(event) {
    let time = event.detail;
    this.setData({
      travelAroundTime:this.formatDate(time),
      showTravel:false
    })
  },
  // 地址二维码弹窗 新增二维码
  onClickRight(){
    this.setData({
      codeShow:false,
      addressList_caller :'express'
    })
    let yz_addressList = this.selectComponent('#yz_addressList');
    yz_addressList.showAddAddress('iscode');
  },
  code_confirmSelectAddress(e){
    let info;
    if (e.detail.loc) {
      info = e.detail.form;
    } else {
      info = e.detail;
    }
    if(this.data.addressCodeClick == 1) return;
    this.data.addressCodeClick = 1
    this._setAddressViewData(info);
    this._requestByAddress();
  },
  confirmSelectAddress(e) {
    let info;
    if (e.detail.loc) {
      info = e.detail.form;
    } else {
      info = e.detail;
    }
    if(this.data.addressList_caller == "express"){
      this._setAddressViewData(info);
      this._requestByAddress();
      this.setData({
        showAddressList: false,
      });
    } else if(this.data.addressList_caller == "invoice") {
      this.selectComponent('.invoicePop').setAddress(info);
      this.setData({
        showAddressList: false,
      });
    }

  },
  //设置地址界面
  _setAddressViewData(model) {
    if (model == undefined || model == "" || model == []) {
      return;
    }

    if (this.options.tag === "cake") {
      this.setData({
        cakeCity: model.city,
        shopDetail:'',
        shopName:'',
        shopId:''
      });
      this.getRule();
    }

    //设置地址id
    this.data.currentAddId = model.id || model.address_id;
    this.setData({
      currentAddress:model,
      realname: app._isTextEmpty(model.username) ? "" : model.username,
      mobile: app._isTextEmpty(model.mobile) ? "" : model.mobile,
      address: app._isTextEmpty(model.province) ? (model.address?model.address:"") : model.province + " " + model.city + " " + model.district + " " + (app._isTextEmpty(model.street) ? "" : model.street + " ") + model.address,
    });
    if (this.data.selected == "11") {
      if (!model.latitude || !model.longitude) {
        // #12172 优化
        app.confirm("将获取您的位置，请确定后重新提交订单", (res)=>{
          if(res){
            this.autoAddress(model)
          }
        }, false);
        return;
      }
    }
  },
  // 同城配送提示当前地址没有经纬度，点击确认自动定位
  autoAddress(model){
    let addressId = model.id;
    this._getLocation((mapdata, e) => {
      let point = app.qqMapTransBMap(parseFloat(e.lng), parseFloat(e.lat));
      let urlStr = app.getNetAddresss("member.member-address.update-location");
      app._getNetWork({
        url: urlStr,
        data:{
          address_id:addressId,
          latitude:point.lat,
          longitude:point.lng
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            model.latitude = point.lat;
            model.longitude = point.lng;
            // 改了经纬度后赋值给当前页面字段
            this.setData({
              currentAddress:model
            })
          } else {
            wx.showToast({
              icon: "none",
              title: "请重新编辑您的地址，在地图上选择您所在的位置",
              duration: 1000,
            });
          }
        },
      });
    });
  },
  //组装优惠券json信息
  _assembleCoupons() {
    let coupons = [];
    for (let i = 0; i < this.data.checkCouponList.length; i++) {
      if (this.data.is_coupon_SELE) {
        //开启折叠优惠券
        let conpon_arr = this.data.checkCouponList[i].has_conpon_id;
        coupons = coupons.concat(conpon_arr.slice(0, this.data.coupons_temp[this.data.checkCouponList[i].coupon_id].num));
        this.setData({
          use_coupon_size: coupons.length,
        });
      } else {
        coupons.push(this.data.checkCouponList[i].id);
      }
    }
    return coupons;
  },
  //组装优惠抵扣信息
  _assembleDeduction() {
    let deductions = [];
    for (let i = 0; i < this.data.checkDeductionList.length; i++) {
      if (this.data.checkDeductionList[i]) {
        deductions.push(this.data.checkDeductionList[i]);
      }
    }
    return deductions;
  },
  _initDiyForm() {
    if (JSON.stringify(this.data.orders_goods) != "{}") {
      //解决填写完表单后，去操作其他会重新请求接口的覆盖了，导致填写记录为空了
      return;
    }
    let orders_goods = {};
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        if (this.data.goodsInfo.orders[j].order_goods[i].diy_form) {
          let model = {};
          model.pre_id = this.data.goodsInfo.orders[j].order_goods[i].pre_id;
          model.diyform_data_id = "";
          orders_goods[model.pre_id] = model;
        }
      }
    }
    this.setData({
      orders_goods: orders_goods,
    });
  },
  findGoodOpen() {
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      if (this.data.goodsInfo.orders[j].camilo_resources_coupon_type) {
        // 卡券商品
        this.setData({
          camilo_resources_coupon_type: this.data.goodsInfo.orders[j].camilo_resources_coupon_type,
        });
        // if (this.data.plugin_setting.yz_supply_camilo_resources.is_default_order_address == 1) {
        //   // 是否开启默认地址
        //   this.setData({
        //     _show_address: true
        //   });
        //   this.data.currentAddId = 1; //地址没有id  写死一个
        //   let {
        //     address,
        //     city,
        //     district,
        //     province,
        //     street,
        //     mobile,
        //     username
        //   } = this.data.plugin_setting.yz_supply_camilo_resources;
        //   this._setAddressViewData({
        //     address,
        //     city,
        //     district,
        //     province,
        //     street,
        //     mobile,
        //     username,
        //     address_id: 1
        //   }); // 设置地址界面
        // }
      }
      if (this.data.bookingShowAddress == '0') {
        //第三方周边游，bookingShowAddress等于0，周边游不需要填写地址，但是商城中台需要填写地址下单
        this.setData({
          _show_address:true
        })
      }
      if (this.options.electricity && this.options.electricity == "electricity") {
        this.setData({
          electricity_Guide: this.data.goodsInfo.orders[j].order_goods[0].pre_id,
          ele_no_showAdress: this.data.goodsInfo.orders[j].order_goods[0] ? this.data.goodsInfo.orders[0].not_show_address : false,
          eleUser: this.data.goodsInfo.orders[j].order_goods[0] ? this.data.goodsInfo.orders[0].user_account : ''
        });
      }
      if (this.data.goodsInfo.orders[j].require_mobile) {
        let _tips = "";
        if (this.data.goodsInfo.orders[j].tips) {
          _tips = this.data.goodsInfo.orders[j].tips.replace(/<img/g, '<img style="width:100%"');
        }
        this.setData({
          recharge_tips: _tips,
          show_recharge_mobile: this.data.goodsInfo.orders[j].order_goods[0].pre_id,
        });
      }
      //油卡充值
      if(this.data.oil_mobile && this.data.oil_account){
        this.data.oil_pre_id = this.data.goodsInfo.orders[j].order_goods[0].pre_id;
      }
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        if (this.data.goodsInfo.orders[j].order_goods[i].diy_form) {
          console.log("有商品开启自定义表单！！！");
          this.data.hasGoodOpenDF = true;
        }
      }
    }
  },
  _checkDiyForm() {
    for (let i in this.data.orders_goods) {
      if (!this.data.orders_goods[i].diyform_data_id) {
        // this.data.submit_active = true;
        return false;
      }
    }
    return true;
  },
  _setDiyForm(pre_id, diyform_data_id) {
    for (let i in this.data.orders_goods) {
      if (this.data.orders_goods[i].pre_id == pre_id) {
        this.data.orders_goods[i].diyform_data_id = diyform_data_id;
        this.setData({
          orders_goods: this.data.orders_goods,
        });
        return;
      }
    }
  },
  _findDiyForm(pre_id) {
    for (let i in this.data.orders_goods) {
      if (this.data.orders_goods[i].pre_id == pre_id) {
        return this.data.orders_goods[i].diyform_data_id;
      }
    }
    return false;
  },
  _assembleDiyForm() {
    let orders_goods = [];
    for (let i in this.data.orders_goods) {
      orders_goods.push(this.data.orders_goods[i]);
    }
    return orders_goods;
  },

  onTELChange(e) {
    this.setData({
      recharge_mobile: e.detail,
    });
  },
  assembleGoodsTELData() {
    //组装商品话费慢充信息
    let newGoodsDF = [];
    let modelDF = {};

    if (this.options.electricity == "electricity") {
      modelDF.pre_id = this.data.electricity_Guide;
      modelDF.account_id = this.options.account_id;
    } else if(this.data.oil_account && this.data.oil_mobile){  //油卡充值
      modelDF.pre_id = this.data.oil_pre_id;
      modelDF.account = this.data.oil_account;
      modelDF.mobile = this.data.oil_mobile;
    } else {
      modelDF.pre_id = this.data.show_recharge_mobile;
      modelDF.mobile = this.data.recharge_mobile;
    }
    newGoodsDF.push(modelDF);
    return newGoodsDF;
  },

  //设置界面
  _setViewData(data, cart_ids) {
    // 配销券 tag:distribution_coupon
    if( this.data._root_tag == 'distribution_coupon' && data.distribution_coupon.length > 0 ){
      this.setData({
        distribution_couponData:data.distribution_coupon
      })
    }
    // 中台租赁租期获取
    // console.log('中台租赁租期获取',data.yz_lease_goods)
    if(this.data._root_tag == 'yzlease' && data.yz_lease_goods){
      this.setData({
        rentTime:data.yz_lease_goods.rent_term,
        isRightChoose:true,
        agreeCon:data.yz_lease_goods.policy
      })
      console.log(this.data.rentTime,this.data.isRightChoosem,this.data.agreeCon)
    }
    this.setData({
      _show_address: this.isOrderAddress_M(data.orders),
      recommend_goods: data.dispatch.recommend_goods ? data.dispatch.recommend_goods : []
    });
    if (data.is_agency_restock && data.is_agency_restock == 1) {
      this.setData({
        _show_address: true,
      });
    }
    if (this.data._show_address) { //跟H5一样有这个判断
      this.setData({
        selected: 0
      });
    }
    this._setAddressViewData(data.dispatch.default_member_address); //设置地址界面

    if(!this.data.consigneeName){
      this.setData({
        consigneeName: data.dispatch.custom_data?.custom_consignee,
        consigneeMobile: data.dispatch.custom_data?.custom_phone
      });
    }
    

    this._initDiyForm();
    if (data.discount && data.discount.default_deduction && data.discount.default_deduction != 0) {
      this.data.default_deduction = data.discount.default_deduction;
    }

    this.order_data = data.orders;
    // if (this.data.default_deduction != 0) {
      // 默认积分抵扣要获取order_deductions里checked=true的传给第二次接口
      for (let i = 0; i < data.orders.length; i++) {
        let arr = data.orders[i].order_deductions;
        let service_fees = this.order_data[i].order_service_fees;
        if (!(data.orders[i].order_deductions instanceof Array)) {
          arr = Object.values(data.orders[i].order_deductions);
        }
        arr.map((item) => {
          if (item.checked) {
            this._screenDiscount(data.orders[i], item);
          }
        });
        if (service_fees) {
          service_fees.map(item => {
            if (item.checked && !this.data.service_fee[this.order_data[i].pre_id]) {
              this.data.service_fee[this.order_data[i].pre_id] = [];
              this.data.service_fee[this.order_data[i].pre_id].push(item.code);
              this.serviceFeesHandle(this.order_data[i], item);
            }
          });
        }
      }
    // }

    // let that = this;
    this.findGoodOpen(); // 循环订单列表是否开启表单和慢充
    if (!this.data.getParams_status) {
      this.data.getParams_status = true;
      this.getParams(cart_ids);
    }
    this.checkOrders(data); //判断有订单是否有绑定域名

    this.data.dispatch.forEach((items, i) => {
      if(this.data._root_tag == 'machine') return
      if (items.dispatch_type_id == 8) {
        if (JSON.stringify(this.data.defaultSelfCarry) == "{}") {
          this._getLocation(() => {
            this.getList("shop");
          });
        }
      }
      if (items.dispatch_type_id == 12) {
        console.log("有门店自提点配送方式，请求定位获取自提点列表");
        if (!this.data.o2oSelfCarry.id) {
          this._getLocation(() => {
            this.getList("o2o");
          });
        }
      }
    });
    this.setData({
      order_data: data.orders,
      price: data.total_price, //设置总价格（合计）
      total_items: data.amount_items,
      discount_amount_items: data.discount_amount_items,
      service_fee_items: data.service_fee_items,
      tax_fee_items:data.tax_fee_items,
      service: data.orders[0].order_fees,
      none_loc: true,
      clicktag: 0,
    });
    if(this.data._root_tag == 'reserve'){
      this.setData({
        delivery_information:data.delivery_information
      })
    }
    if (this.data._root_tag == "store" && this.data.price < 0) {
      wx.showToast({
        icon: "none",
        title: "下单错误",
        duration: 1500,
      });
    }
    if (data.dispatch.use_wechat_address) {
      this.setData({
        use_wechat_address: data.dispatch.use_wechat_address
      });
    }
    if(data.is_diy_form_jump == 1){
      this.setData({
        is_diy_form_jump:data.is_diy_form_jump
      })
    }
    this.getDistributionInfo(data.last_deliver_user_info);
    if(data.address_code){
      this.setData({
        show_add_address : data.address_code.show_add_address?data.address_code.show_add_address:false
      })
    }
    this.first_default =  data.first_default;//是否首次请求，之后的请求都要回传这个参数。没有传这个参数的订单全部按默认首次请求处理
  },
  isOrderAddress_M(_data) {
    //判断是否有订单需要填写地址，有一单需要填写地址则需要填写地址才可以下单
    if(this.options.device_id) return true
    //return false 提交订单需要填写地址
    for (let j = 0; j < _data.length; j++) {
      if (this.data.phone_bill_pro_goods) {
        if (!_data[j].not_show_address) {
          return false;
        }
      } else if(this.data.oil_account && this.data.oil_mobile){
        if (!_data[j].not_show_address ) {
          return false;
        }
      } else if (this.options.storeType == 'horizon'){
        return !_data[j].not_show_address;
      } else if (this.data.bookingShowAddress) {
         //如果是周边游，bookingShowAddress等于1是周边游第三方需要填写地址
         return false;
      }else {
        if (!_data[j].need_address) {
          console.log("有订单需要填写地址");
          return false;
        }
      }

    }
    return true;
  },
  checkOrders(data) {
    for (let i = 0; i < data.orders.length; i++) {
      if (data.orders[i].plugin_id === 58) {
        this.setData({
          plugin_id: 58,
        });
      }
    }

    for (let i = 0; i < data.orders.length; i++) {
      if ("domain" in data.orders[i]) {
        this.setData({
          isDomain: true,
          domain: data.orders[i].domain,
        });
      } else {
        this.setData({
          isDomain: false,
        });
        return;
      }
    }
  },
  // 整合了发票、是否显示个人信息接口
  getParams(cart_ids) {
    let json = {};
    let that = this;
    if (this.data._root_tag == "store" && !cart_ids) {
      return;
    } else if (this.data._root_tag == "store" && cart_ids) {
      this.setData({
        _cart_ids: cart_ids,
      });
    }
    let good_ids = [];
    // 不清楚this.data.options.cart_ids这个字段作用，但是这个字段导致选择完自提点后返回报错，打印这个cart_ids为字符串得undefined
    if (this.data.options.cart_ids && this.data.options.cart_ids != "undefined") {
      this.setData({
        _cart_ids: this.data.options.cart_ids ? JSON.parse(this.data.options.cart_ids) : [],
      });
    }

    if (this.data.isCartsOrder) {
      // 购物车商品下单的循环商品
      for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
        for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
          good_ids.push(this.data.goodsInfo.orders[j].order_goods[i].goods_id);
        }
      }
    } else {
      if (this.data.options.goodsId) {
        this.setData({
          _goodsId: Number(this.data.options.goodsId),
        });
      }
      good_ids.push(this.data._goodsId);
    }
    let urlStr = app.getNetAddresss("from.div-from.get-params");
    json = {
      goods_ids: JSON.stringify(good_ids),
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (that.options.type != "groupBuy_open" || that.options.type != "groupBuy_join") {
            //拼购显示自己的支付协议
            that.setData({
              isGetAgreementPay: true,
              AgreementPay: res.data.getPayProtocol ? res.data.getPayProtocol : "",
            });
          }
          this.setData({
            freightExplain: res.data.freightExplain,
            deliveryTimeParams: res.data.deliveryTime
          });
          try {
            that.setData({
              storeSearchBtn: res.data.storeSearch || {},
              openCueCoupon: res.data.getCouponSet == 0 ? false : true, //是否开启下单优惠券提示
            });
            that._checkTaxGoods(res.data.isDisplay);
            if (res.data.getMemberInfo) {
              that._getMemberInfo(res.data.getMemberInfo);
            }
            // if (res.data.explain) {
            //   that._getExplain(res.data.explain);
            // }
            that.getInvoice(res.data.sinvoice);
          } catch (error) {
            console.log(error);
          }
        } else {
          that.setData({
            isGetAgreementPay: false,
          });
        }
        if(that.data.machineId){
          that.setData({_show_address:true})
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  // 发票数据
  getInvoice(data) {
    let address = {
      realname: this.data.realname,
      mobile: this.data.mobile,
      address: this.data.address
    }
    this.selectComponent('.invoicePop').initData({sinvoice: data, address});
  },
  subInvoice(data) {
    // 弹窗获取发票数据
    this.setData({
      invoice_list: data.detail, //72638
    });
  },

  //初始化优惠券
  _initCoupon(data) {
    if (data.deduction_lang) {
      this.setData({
        deduction_lang: data.deduction_lang
      });
    }
    this.setData({
      isShowCoupon: data.whether_show_coupon == "1" ? true : false,
    });
    let coupon = data.member_coupons;
    this.setData({
      is_coupon_SELE: data.coupon_show == "1" ? true : false,
    });
    this.setData({
      coupon_size: coupon.length,
    });
    if (coupon != undefined && coupon != "" && coupon != null) {
      if (this.data.is_coupon_SELE) {
        //按过期时间排序
        let arr2 = coupon.sort((a, b) => {
          return a.expired_at - b.expired_at;
        });
        this.initSelectCoupon(arr2);
      } else {
        this.setData({
          coupons: coupon,
        });
      }
    }
  },
  //初始化带有默认选中优惠券
  defaultSelectCoupon(coupon) {
    let checkCouponList = [];
    coupon.forEach((item, ind) => {
      if (item.checked == true) {
        checkCouponList.push(item);
      }
    });
    this.setData({
      coupon_size: coupon.length,
      coupons: coupon,
      use_coupon_size: checkCouponList.length,
      checkCouponList: checkCouponList,
    });
  },
  //折叠优惠券
  initSelectCoupon(coupon) {
    let coupon_data = coupon;
    let result = [];
    let temp = {};

    for (let i = 0; i < coupon_data.length; i++) {
      let num = 0; //同类型已选中并符合使用条件的优惠券数量
      let valid = 0; //最高限制使用数量
      let has_conpon_id = [coupon_data[i].id];
      if (coupon_data[i].checked) {
        num++;
      }
      if (coupon_data[i].valid) {
        valid++;
      }
      for (let j = i + 1; j < coupon_data.length; j++) {
        if (coupon_data[i].coupon_id == coupon_data[j].coupon_id) {
          if (coupon_data[j].checked) {
            num++;
          }
          if (coupon_data[j].valid) {
            valid++;
          }
          has_conpon_id.push(coupon_data[j].id);
          coupon_data.splice(j, 1);
          j--;
        }
      }
      let _data = coupon_data[i];
      _data.has_conpon_id = has_conpon_id;
      _data.valid_num = valid;
      result.push(_data);
      temp[coupon_data[i].coupon_id] = {};
      temp[coupon_data[i].coupon_id].num = num;
    }
    this.setData({
      coupons_temp: temp,
      coupons: result,
    });
  },
  //配销券
  showDistribution_coupon(){
    this.setData({
      distribution_couponSpecs:true
    })
  },
  // 关闭配销券
  closeDistribution_coupon(){
    this.setData({
      distribution_couponSpecs:false
    })
  },
  // 选择配销券
  ChangeDistribution(e){
    let {id,valid} = e.currentTarget.dataset;
    if(!valid){
        app.tips("该配销券不可选")
      return
    }
    if(this.data.distribution_coupon_ids.includes(id)){
      this.data.distribution_coupon_ids.splice(this.data.distribution_coupon_ids.indexOf(id), 1);
    }else{
      this.data.distribution_coupon_ids.push(id);
    }
    this.setData({
      distribution_coupon_ids : this.data.distribution_coupon_ids
    })
    this.handleBuy(2);
  },
  changeConpon(e) {
    let valObj = e.target.dataset.item;
    let num = e.detail;
    let index = e.target.dataset.index;
    if (num > valObj.valid_num) {
      wx.showToast({
        icon: "none",
        title: "使用张数已达上限",
        duration: 1000,
      });
      clearTimeout(this.data.timer);
      this.data.timer = setTimeout(() => {
        // 注意此时修改 value 后会再次触发 change 事件
        this.data.coupons_temp[valObj.coupon_id].num = valObj.valid_num;
        this.setData({
          coupons_temp: this.data.coupons_temp,
        });
      }, 200);
      return;
    } else if (num == "" || num == undefined || num == 0) {
      wx.showToast({
        icon: "none",
        title: "暂不使用请取消勾选",
        duration: 1000,
      });
      return;
    } else {
      clearTimeout(this.data.timer);
      this.data.coupons_temp[valObj.coupon_id].num = num;
      this.setData({
        coupons_temp: this.data.coupons_temp,
      });
    }

    // clearTimeout方法，以便控制连续触发带来的无用调用
    let value = {
      detail: true,
      currentTarget: {
        dataset: {
          index: index,
          item: valObj,
        },
      },
    };
    if (this.data.timeoutId) {
      clearTimeout(this.data.timeoutId); // 先清除之前的延时，并在下面重新开始计算时间
    }
    this.data.timeoutId = setTimeout(() => {
      // 100毫秒以后执行方法
      this.selectCoupon(value);
    }, 1000); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
  },

  //提货人输入
  infonamebtn(e) {
    let infoname = e.detail;
    this.setData({
      "linkinfo.name": infoname,
    });
  },
  infonameclear() {
    this.setData({
      "linkinfo.name": "",
    });
  },
  infomobileclear() {
    this.setData({
      "linkinfo.mobile": "",
    });
  },
  //提货人手机输入
  infomobilebtn(e) {
    let infomobile = e.detail;
    this.setData({
      "linkinfo.mobile": infomobile,
    });
  },
  //选择地址后重新计算数据
  _requestByAddress() {
    //重新计算
    this.handleBuy(1);
  },

  //判断是否选择权益商品
  _judgeIsRight() {
    if (this.data.isOpenRight) {
      this.setData({
        isRightChoose: false,
      });
    } else {
      this.setData({
        isRightChoose: true,
      });
    }
  },
  //权益商品选择事件
  rentSelect(e) {
    let isOpenRight = e.detail;
    this.setData({
      isOpenRight: isOpenRight,
    });
    //1.判断是否选择权益商品，有则租期按照会员权益日期计算
    this._clearStorage();
    this._judgeIsRight();
    if (this.data.isOpenRight) {
      let arr = [];
      this.data.order_data.forEach((val) => {
        val.order_goods.forEach((item) => {
          let obj = {
            goods_id: item.goods_id,
            total: item.total,
          };
          arr.push(obj);
        });
      });
      wx.setStorage({
        key: "rentTimeRight",
        data: JSON.stringify(arr),
      });
      this._getRentDataActionCart(JSON.stringify(arr), []);
    } else if (!this.data.isOpenRight) {
      this.setData({
        currentIndex: "999",
      });
      this._getRentDataActionCart([], []);
    }
  },
  //清除租赁localstorage
  _clearStorage() {
    wx.removeStorage({
      key: "rentTimeSelf",
    });
    wx.removeStorage({
      key: "rentTimeChoose",
    });
    wx.removeStorage({
      key: "rentTimeRight",
    });
  },
  kfeeChange(e){
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = e.currentTarget.dataset.orindex;
    let pre_id = this.data.order_data[orindex].pre_id;
    let item = e.currentTarget.dataset.kfee;
    if(e.detail == false){
      this.setData({
        ["taxInclusive." + pre_id]: [item.fee_code],
      })
    }else{
      this.setData({
        ["taxInclusive." + pre_id]: [],
      })
    }
    this.serviceFeesHandle(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    //重新计算
    this.handleBuy(2);
  },
  switchChange(e) {
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = e.currentTarget.dataset.orindex;
    let pre_id = this.data.order_data[orindex].pre_id;
    let item = e.currentTarget.dataset.item;
    let codeind = e.currentTarget.dataset.codeind;

    if (item.checked) {
      this.setData({
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].checked']: false,
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].show']: false,
        ["service_fee." + pre_id]: [],
      });
    } else {
      this.setData({
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].checked']: true,
        ['order_data[' + orindex + '].order_service_fees[' + codeind + '].show']: true,
        ["service_fee." + pre_id]: [item.code],
      });
    }
    this.serviceFeesHandle(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    //重新计算
    this.handleBuy(2);
  },
  //抵扣选择响应
  discountHandle(e) {
    let dischecked = e.detail;
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = e.currentTarget.dataset.orindex;
    let tag = e.currentTarget.dataset.tag;
    if (!this.data.none_loc) {
      // 超出门店配送范围不可以使用积分抵扣
      dischecked = false;
    }

    if (tag == "discount") {
      if (Object.prototype.toString.call(this.data.order_data[orindex].order_deductions) == "[object Object]") {
        // object要用.的方式调用
        this.setData({
          ["order_data[" + orindex + "].order_deductions." + dindex + ".checked"]: dischecked,
        });
      } else if (Object.prototype.toString.call(this.data.order_data[orindex].order_deductions) == "[object Array]") {
        this.setData({
          ["order_data[" + orindex + "].order_deductions[" + dindex + "].checked"]: dischecked,
        });
      }
      this._screenDiscount(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    } else if (tag == "serviceFee") {
      let pre_id = this.data.order_data[orindex].pre_id;
      this.setData({
        ["service_fee." + pre_id]: e.detail,
      });

      this.serviceFeesHandle(this.data.order_data[orindex], this.data.order_data[orindex].order_deductions[dindex]);
    }

    //重新计算
    this.handleBuy(2);
  },
  // 留言
  noteHandle(e) {
    let preid = e.target.dataset.preid;
    let item = e.target.dataset.item;
    let val = e.detail.value;
    this.setData({
      ["note." + preid]: val,
    });
    // 触发抵扣事件
    this.deductionListHandle(item);
  },
  //筛选抵扣
  _screenDiscount(item, value) {
    this.deductionListHandle(item, value);
  },
  serviceFeesHandle(item, value) {
    //服务费、运费复选框
    this.deductionListHandle(item);
  },

  deductionListHandle(item, value) {
    let checkDeductionList = this.data.checkDeductionList;
    let service_fee = this.data.service_fee;
    let taxInclusive = this.data.taxInclusive||[];
    let note = this.data.note;
    let isHasPreId = false;

    if (checkDeductionList.length > 0) {
      checkDeductionList.map((deduction, index) => {
        if (deduction && deduction.pre_id == item.pre_id) {
          isHasPreId = true;
          if (value && value.checked) {
            // 选中的时候检查是否有对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) == -1) {
              deduction.deduction_ids.push(value.code);
            }
          } else if (value && !value.checked) {
            // 取消选中的时候检查去掉对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) > -1) {
              deduction.deduction_ids.splice(deduction.deduction_ids.indexOf(value.code), 1);
            }
          }

          // 留言和安装选项重新赋值
          deduction.note = note[item.pre_id];
          deduction.service_fee = service_fee[item.pre_id];
          deduction.tax_fee = taxInclusive[item.pre_id];
        }
      });
    }
    if (!isHasPreId) {
      checkDeductionList.push({
        deduction_ids: value && value.code ? [value.code] : [],
        pre_id: item.pre_id,
        note: note[item.pre_id],
        service_fee: service_fee[item.pre_id],
        tax_fee:taxInclusive[item.pre_id]
      });
    }
    this.setData({
      checkDeductionList
    });
  },

  //选择自定义租期
  rentSelfChoose() {
    this._clearStorage();
    this.setData({
      currentIndex: "999",
    });
    this.setData({
      rentShow: true,
    });
  },
  rentShowClose(event) {
    if (event.detail === "confirm") {
      if (app._isTextEmpty(this.data.tenancy)) {
        wx.showToast({
          icon: "none",
          title: "租期不能为空",
          duration: 1000,
        });
        return;
      }
      let obj = {
        days: this.data.tenancy,
        lease_term_id: 0,
      };
      // 中台租赁商品
      if(this.data._root_tag == 'yzlease'){
        this.setData({
          'yz_lease_time.days':this.data.tenancy,
          'yz_lease_time.lease_term_id':0,
          rentShow:false,
        })
        this.handleBuy();
        return
      }
      wx.setStorage({
        key: "rentTimeSelf",
        data: JSON.stringify(obj),
      });
      this._getRentDataActionCart([], JSON.stringify(obj));
      // 异步关闭弹窗
      setTimeout(() => {
        this.setData({
          rentShow: false,
        });
      }, 1000);
    } else {
      this.setData({
        rentShow: false,
      });
    }
  },
  //自定义租期数值绑定
  rentShowinp(e) {
    let rentval = e.detail;
    this.setData({
      tenancy: rentval,
    });
  },
  //自定义租期值清除
  rentclear() {
    this.setData({
      tenancy: "",
    });
  },
  //选择租期
  rentTimeChoose(e) {
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    // 中台租赁商品
    if(this.data._root_tag == 'yzlease'){
      this.setData({
        currentIndex:index,
        'yz_lease_time.days':item.term_days,
        'yz_lease_time.lease_term_id':item.id
      })
      this.handleBuy();
      return
    }
    if (this.data.currentIndex == index) {
      this.setData({
        currentIndex: "999",
      });
      this._clearStorage();
      this._getRentDataActionCart([], []);
    } else {
      this._clearStorage();
      this.setData({
        currentIndex: index,
      });
      let obj = {
        days: 0,
        lease_term_id: item.id,
      };
      wx.setStorage({
        key: "rentTimeChoose",
        data: JSON.stringify(obj),
      });
      this._getRentDataActionCart([], JSON.stringify(obj));
    }
  },

  //优惠券
  showCoupon() {
    if (this.data.coupon_size == 0) {
      wx.showToast({
        icon: "none",
        title: "暂无优惠券使用",
        duration: 1500,
      });
      return;
    }
    this.setData({
      popupCouponSpecs: true,
    });
  },
  chooseCoupon(e) {
    const index = e.currentTarget.dataset.index;
    const checkbox = this.selectComponent(`.coupon-checkboxes-${index}`);
    checkbox.toggle();
  },
  //选择优惠券
  selectCoupon(e) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    this.setData({
      ["coupons[" + index + "].checked"]: couponBol,
    });
    this._screenCoupon(couponBol, item, e.type);
    //设置view
    this._setCouponView();
    //重新计算
    this.handleBuy(2);
  },
  //筛选数据优惠券状态
  _screenCoupon(couponBol, valObj, type) {
    let tarValue = valObj;
    let checkCouponList = this.data.checkCouponList;
    if (this.data.checkCouponList.length > 0) {
      for (let i = 0; i < this.data.checkCouponList.length; i++) {
        if (this.data.checkCouponList[i].id == tarValue.id) {
          checkCouponList.splice(i, 1);
        }
      }
    }
    if (this.data.is_coupon_SELE && type) {
      //开启折叠优惠券并且为点击复选框为选中状态
      this.data.coupons_temp[tarValue.coupon_id].num = couponBol ? 1 : 0;
      this.setData({
        coupons_temp: this.data.coupons_temp
      });
    }
    if (couponBol) {
      //选中添加
      checkCouponList.push(tarValue);
    } else {
      //取消选中
      this.setData({
        cup_notice: true
      });
    }
    this.setData({
      checkCouponList: checkCouponList
    });
  },
  //设置view
  _setCouponView() {
    this.setData({
      use_coupon_size: this.data.checkCouponList.length,
    });
  },
  mustSelectCoupon() {
    // 后台设置，下单前判断有优惠券数量但没使用时，是否提示并展开选择优惠券弹窗，只提示一次！
    if (this.data.openCueCoupon && this.data.coupon_size > 0 && this.data.use_coupon_size < 1 && !this.data.isCueCoupon) {
      //显示优惠券列表弹窗
      // 按钮文字改变
      this.setData({
        isCueCoupon: true,
        popupCouponSpecs: true,
      });
      return true;
    }
    return false;
  },
  //关闭优惠卷
  couponclose() {
    this.setData({
      popupCouponSpecs: false,
    });
  },
  //租赁协议
  agreementbtn(e) {
    let agreeBol = e.detail;
    this.setData({
      agreement: agreeBol,
    });
  },
  //租赁弹窗显示
  showAgreement() {
    this.setData({
      agreementShow: true,
    });
  },
  agreementClose() {
    this.setData({
      agreementShow: false,
    });
  },
  toSite() {
    wx.navigateTo({
      url: "/packageE/others/application_market/binding_site/binding_site?plugin_id=" + this.data.plugin_id,
    });
  },

  //获取模板id
  getTemplate(code) {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 1,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray: array,
          });
          if (that.data.TemplateArray.length > 0) {
            wx.requestSubscribeMessage({
              tmplIds: that.data.TemplateArray,
              success(res) {
                that.setData({
                  clickMiniTemplate: true
                });
                that.submitBtn(code);
              },
              fail(err) {
                that.submitBtn(code);
              },
            });
          } else {
            that.submitBtn(code);
          }
        } else {
          Toast(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //提交订单
  submit() {
    let code = this.data.address_codeEnable?true:false;
    if (this.data.yz_subscribe_disabled) return;
    if (this.data.clickMiniTemplate) {
      this.submitBtn(code);
    } else {
      this.getTemplate(code);
    }

  },
  getDiyForm(){
    // if(this.data.hasGoodOpenDF && this._checkDiyForm()){
    //   // 有开启表单
    //   let orders = this.data.order_data[this.data.order_data.length -1];
    //   let ind ;
    //   for(let i =0;i<orders.order_goods.length;i++){
    //     if(orders.order_goods[i].diy_form){
    //       console.log(orders.order_goods[i].diy_form)
    //       ind = i
    //       this.data.diyform.form_id = orders.order_goods[i].diy_form.form_id
    //     }
    //   }
    //   this.setData({
    //     "diyform.form_id": orders.order_goods[ind].diy_form.form_id,
    //     "diyform.pre_id": orders.order_goods[ind].pre_id,
    //   });
    //   if (this._findDiyForm(orders.order_goods[ind].pre_id)) {
    //     let diyform_data_id = this._findDiyForm(orders.order_goods[ind].pre_id);
    //     this.setData({
    //       "diyform.diyform_data_id": diyform_data_id,
    //     });
    //   }
    //   console.log(this.data.diyform,'diyform')
    //   this.setData({
    //     codeShow : true
    //   })
    // }else{
      // address: encodeURIComponent(JSON.stringify(this.data.currentAddress)),
      this.setData({
        codeShow : true
      })
      let address = this.selectComponent('#yz_showAddress');
      address.code_editAddress(this.data.currentAddress);
      address.getIsOpenAddress();
    // }
  },
  onClickLeft(){
    this.setData({
      codeShow:false
    })
  },
  checkDispatch() {
    if(this.data._root_tag == 'machine') return true;
    if (this.data.selected == 8 || this.data.selected == 12 || this.data.selected == 15) {
      if (app._isTextEmpty(this.data.linkinfo.name)) {
        wx.showModal({
          title: "提示",
          content: "请填写提货人姓名",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {},
        });
        this.data.submit_active = true;
        return false;
      }
      if (app._isTextEmpty(this.data.linkinfo.mobile)) {
        wx.showModal({
          title: "提示",
          content: "请输入提货人手机",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {},
        });
        this.data.submit_active = true;
        return false;
      }
    }

    if (this.data.selected == 8 || this.data.selected == 12) {
      if ((this.data.selected == 8 && app._isTextEmpty(this.data.defaultSelfCarry)) || (this.data.selected == 12 && app._isTextEmpty(this.data.o2oSelfCarry))) {
        wx.showToast({
          title: "该地区暂无自提点",
          duration: 1000,
          icon: "none",
        });
        return false;
      }
      if ((this.data.selected == 8 && app._isTextEmpty(this.data.defaultSelfCarry.id)) || (this.data.selected == 12 && app._isTextEmpty(this.data.o2oSelfCarry.id))) {
        wx.showModal({
          title: "提示",
          content: "请选择自提点",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {},
        });
        this.data.submit_active = true;
        return false;
      }

      //保存自提点信息到本地，任务编号: 35632
      let _memberInfoes = {
        distributionUserName: this.data.linkinfo.name ? this.data.linkinfo.name : "",
        distributionUserMobile: this.data.linkinfo.mobile ? this.data.linkinfo.mobile : "",
      };
      try {
        wx.setStorageSync("selfCarryInfo", JSON.stringify(_memberInfoes));
      } catch (e) {
        console.log(e);
      }
    }

    if (this.data.store_info.delivery_information == 1) {
      if (this.data.selected == "2" && (app._isTextEmpty(this.data.linkinfo.name) || app._isTextEmpty(this.data.linkinfo.mobile))) {
        wx.showToast({
          icon: "none",
          title: "请输入提货人信息",
          duration: 1500,
        });
        return false;
      }
      if (this.data.selected == "2" && !/^[0-9]{1,}$/.test(this.data.linkinfo.mobile)) {
        wx.showToast({
          icon: "none",
          title: "请输入正确的联系电话",
          duration: 1500,
        });
        this.data.submit_active = true;
        return false;
      }
    }

    if (!this.data._show_address && (this.data.selected == 0 || this.data.selected == 1 || this.data.selected == 3) && !this.data.ele_no_showAdress && !this.data.reserve_order) {
      if ((this.data.selected == 0 || this.data.selected == 1) && this.data.use_wechat_address) {
        // 页面设计插件和商城设置 - 订单设置 - 调用微信地址开启了 只用于快递
        if (app._isTextEmpty(this.data.design_info.userName)) {
          app.tips('请输入收货人姓名');
          this.data.submit_active = true;
          return false;
        }
        if (app._isTextEmpty(this.data.design_info.telNumber)) {
          app.tips('请填写收货手机号');
          this.data.submit_active = true;
          return false;
        }
        if (app._isTextEmpty(this.data.userAdress)) {
          app.tips('请选择所在区域');
          this.data.submit_active = true;
          return false;
        }
        if (app._isTextEmpty(this.data.design_address)) {
          app.tips('请输入街道、楼牌号等');
          this.data.submit_active = true;
          return false;
        }
        return true;
      }
      if (app._isTextEmpty(this.data.currentAddId) && this.data._root_tag !== 'machine') {
        wx.showModal({
          title: "提示",
          content: "请选择收货地址",
          showCancel: false,
          confirmText: "确定",
          confirmColor: "#000000",
          success: (res) => {
            this.showAddress();
          },
        });
        this.data.submit_active = true;
        return false;
      }
    }



    return true;
  },
  checkSubmit() {
    if(this.data.deliveryTimeParams.status == 1) {
      if (!this.data.shop_delivery_day||!this.data.shop_delivery_time) {
        wx.showToast({
          icon: "none",
          title: "请填写配送日期/时间",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.mustSelectCoupon()) {
      // 提示优惠券【51723】
      return false;
    }

    if (this.data.isDomain) {
      if (app._isTextEmpty(this.data.domain)) {
        wx.showToast({
          icon: "none",
          title: "请绑定站点",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.data.cpstype == "1" && this.data.cpsTxt == "") {
      wx.showToast({
        title: "请输入帐号",
        duration: 1000,
        icon: "none",
      });
      return false;
    }

    // 手机慢充
    if (this.data.show_recharge_mobile && !this.data.recharge_mobile) {
      wx.showToast({
        icon: "none",
        title: "请输入充值手机号码！",
        duration: 1500,
      });
      return false;
    } else if (this.data.show_recharge_mobile && this.data.recharge_mobile) {
      let reg_txt = /^[1][0-9]{10}$/;
      if (!reg_txt.test(this.data.recharge_mobile)) {
        wx.showToast({
          icon: "none",
          title: "请输入正确的充值手机号码！",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.data.reserve_order != null) {
      if (this.data.reserve_tel_name == '') return app.tips("请输入联系人");
      if (this.data.reserve_mobile == '') return app.tips("请输入联系电话");
    }

    if (this.data.camilo_resources_coupon_type == 1) {
      // 卡券商品
      if (!this.data.recharge_number) {
        return app.tips("请输入充值账号");
      }
    }

    if (this.options.tag == "newRetail" && this.options.retailState == 3 && this.data.price == 0) {
      //新零售-自由发货下单不能为0
      wx.showToast({
        icon: "none",
        title: "价格有误",
        duration: 1500,
      });
      this.data.submit_active = true;
      return false;
    }

    if (this.data.hasGoodOpenDF && !this._checkDiyForm()) {
      if(this.data.is_diy_form_jump == 0){
        wx.showToast({
          icon: "none",
          title: "请先填写表单",
          duration: 1500,
        });
        this.data.submit_active = true;
        return false;
      }
      if(this.data.is_diy_form_jump == 1){
        let arrA = this.data.order_data;
        for(let i = 0;i<arrA.length;i++){
          for(let g = 0;g<arrA[i].order_goods.length;g++){
            if(arrA[i].order_goods[g].diy_form && !arrA[i].order_goods[g].diy_form.diyform_data_id){
              this.showDyForm(arrA[i].order_goods[g].diy_form.form_id,arrA[i].order_goods[g].pre_id)
              return false;
            }
          }
        }
      }
    }

    if (!this.checkDispatch()) {
      return false;
    }

    if (this.data.AgreementPay && !this.data.isRent) {
      if (!this.data.agreementPay) {
        wx.showToast({
          icon: "none",
          title: "请勾选支付协议",
          duration: 1500,
        });
        return false;
      }
    }

    if (this.data.isRent && !this.data.agreement) {
      wx.showToast({
        icon: "none",
        title: "请勾选租赁协议",
        duration: 1500,
      });
      this.data.submit_active = true;
      return false;
    }

    return true;
  },
  showDyForm(form_id,pre_id){
    this.setData({
      "diyform.form_id": form_id,
      "diyform.pre_id": pre_id,
    });
    if (this._findDiyForm(pre_id)) {
      let diyform_data_id = this._findDiyForm(pre_id);
      this.setData({
        "diyform.diyform_data_id": diyform_data_id,
      });
    }
    this.setData({
      diyShow: true,
    });
  },
  submitBtn(code = false) {
    if (!this.checkSubmit()) {
      return;
    }
    if ( this.data._root_tag == 'tourAround'  && this.data.bookingShowAddress == "0") { //周边游开启默认地址的时候，不需要填写表单地址
      this.submitBtnPost();
      return;
    }
    if(code && this.data.selected == 1){
      this.getDiyForm()
      return
    }
    if(this.data.use_wechat_address && (this.data.selected == '1' || this.data.selected == '0') && !this.data._show_address && !this.data.addressCheckStatus){
      this.checkWxAdress(this.data.design_info,true);
      return
    }
    this.submitBtnPost();
  },
  submitBtnPost(){
    let that = this;
    let json = this._assembleJson();
    if (this.data.store_id && this.options.tag != "reserve") {
      if (this.isHasInstall()) {
        //有勾选了上门安装服务，需要填写经纬度和时间
        if (!this.data.installDate) {
          app.tips("请选择预约时间！");
          return;
        }
        if (!this.data.location && !this.data.location.latitude) {
          app.tips("请选择地理位置！");
          return;
        }
        let live_install_json = {
          live_install: {
            longitude: this.data.location.longitude,
            latitude: this.data.location.latitude,
            reserve_time: this.data.installDate,
            install_comment: this.data.install_comment,
          },
        };
        if(this.options.just_live_install){
          live_install_json.live_install_order_replace_uid = this.options.live_install_order_replace_uid;
          live_install_json.dispatch_type_id = 1;
        }
        Object.assign(json, live_install_json);
      }

    }
    if(this.options.energy_machine_id){
      json.energy_machine_id = this.options.energy_machine_id;
    }
    if (this.options.tag === "tourAround") {
      if (app._isTextEmpty(this.data.customerPhoneNumber)) {
        wx.showToast({
          icon: "none",
          title: "请填写手机号码",
          duration: 1500,
        });
        return false;
      }
      if (app._isTextEmpty(this.data.customerName)) {
        wx.showToast({
          icon: "none",
          title: "请填写姓名",
          duration: 1500,
        });
        return false;
      }
      if (app._isTextEmpty(this.data.idCard) && this.data.orderShowIdCard) {
        wx.showToast({
          icon: "none",
          title: "身份证必填",
          duration: 1500,
        });
        return false;
      }
      if(this.data.orderShowDate == 1 && app._isTextEmpty(this.data.travelAroundTime)) {
        wx.showToast({
          icon: "none",
          title: "请填写使用时间",
          duration: 1500,
        });
        return false;
      }
      if(this.data.bookingShowAddress == '0' && this.data.address == '') {
        wx.showToast({
          icon: "none",
          title: "请设置默认地址",
          duration: 1500,
        });
        this.setData({
          addressList_caller:"express",
          showAddressList:true
        })
        return false;
      }

      json.customerName = this.data.customerName;
      json.customerPhoneNumber = this.data.customerPhoneNumber;
      json.memo = this.data.memo;
      json.idCard = this.data.idCard;
      json.travelDate = this.data.travelAroundTime;
    }
    if(this.options.tag === "cake") {
      if (app._isTextEmpty(this.data.cakeMoblie)) {
        wx.showToast({
          icon: "none",
          title: "请输入订货人手机号",
          duration: 1500,
        });
        return false;
      }
      if (this.data.cakeShipType === 'delivery' || this.data.cakeShipType === 'shop' ) {
        if (app._isTextEmpty(this.data.cakeShipDate)) {
          wx.showToast({
            icon: "none",
            title: "请选择配送日期",
            duration: 1500,
          });
          return false;
        }
        if (app._isTextEmpty(this.data.shipTimeText)) {
          wx.showToast({
            icon: "none",
            title: "请选择配送时间",
            duration: 1500,
          });
          return false;
        }
      }
      json.dispatch_type_id = 0; //不使用旧商城的配送方式
      json.city_cake = this.data.cakeCity;
      json.cake_ship_type = this.data.cakeShipType;
      json.ship_date = this.data.cakeShipDate;
      json.ship_time_text = this.data.shipTimeText;
      json.buyer_phone = this.data.cakeMoblie;
      if(this.data.canTake === '1' || this.data.canTake === 1) { //判断是否有门店自提
        json.cake_shop_id = this.data.shopId;
        json.cake_shop_detail = this.data.shopDetail;
        json.cake_shop_name = this.data.shopName;
      }
    }
    switch (this.data._root_tag) {
    case "store_projects_goods":
      //* 门店核销
      this.data.order_url = "plugin.store-projects.frontend.order.create";
      json.goods_type = "store_projects_goods";
      if(this.data.options.exchange_code_id){ //兑换码日志id
        this.data.order_other_json = {
          exchange_code_id: this.data.options.exchange_code_id
        };
        this.data.pre_order_url = 'plugin.exchange-code.api.goods-buy';
      }
      break;
    }

    if (this.data.selected == "10") {
      if (json.supplier_driver_distribution_address) {
        if (app._isTextEmpty(json.supplier_driver_distribution_address.lat) || app._isTextEmpty(json.supplier_driver_distribution_address.lng)) {
          app.tips('请选择供应商配送定位');
          return;
        }
      }
    }
    if (this.data.selected == "11") {
      // selected == "11" 同城配送
      if (this.data.cityDelivery.distance_type == 3) {
        if (!this.data.cityDelivery_community.id) {
          app.tips("请选择配送社区");
          return;
        }
        json.community_id = this.data.cityDelivery_community.id;
      }
      if (this.data.cityDelivery.future_state == 1) {
        if (!this.data.cityDelivery_deliveryTime.start_time || !this.data.cityDelivery_deliveryTime.end_time) {
          app.tips("请选择配送时间");
          return;
        }
        json.expect_start_time = this.data.cityDelivery_deliveryTime.start_time;
        json.expect_end_time = this.data.cityDelivery_deliveryTime.end_time;
      }

    }
    // 卡券开启不需要地址 #22040
    if(this.data.camilo_resources_coupon_type && this.data.plugin_setting.yz_supply_camilo_resources.is_default_order_address == '0'){
      json.address = '';
    }
    if (this.data.submit_active == true) {
      this.data.submit_active = false;
      let redirectTo = '';
      let urlStr = app.getNetAddresss(this.data.order_url);
      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: json,
          success: (resdata) => {
            let res = resdata.data;
            that.data.submit_active = true;
            if (res.result == 1) {
              that.setData({
                showPage: false,
              });
              wx.showLoading({
                title: "跳转中",
              });
              try {
                wx.setStorageSync("selfCarryInfo", {});
              } catch (e) {console.log(e);}
              if (that.data.iscps) {
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2" + `&iscps=${that.data.iscps ? true : false}`,
                });
                return;
              }
              if (that.options.option_level_id) {
                let name = 'groups';
                if(that.options.plu && that.options.plu == 'ywm') name = 'ywmGroup';
                redirectTo = "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2" + "&name=" + name;
                wx.redirectTo({
                  url: redirectTo,
                });
                return;
              }
              if (that.data.store_id) {
                // 门店
                if(this.options.just_live_install) {
                  return wx.redirectTo({
                    url: "/packageH/installationSever/installationSeverHome/installationSeverHome?status=3"
                  });
                }
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2&store_id=" + that.data.store_id,
                });
                return;
              }
              // 盲盒
              if (that.data._root_tag == "blindBox") {
                wx.redirectTo({
                  url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2&name=" + that.data._root_tag,
                });
                return;
              }
              //周边游支付
              if (that.data._root_tag == "tourAround") {
                let orderJson = {
                  ordersn:res.data.order_sn,
                  api: 'plugin.travel-around.frontend.payment.payment',
                  name:that.data._root_tag
                };
                let url = `../orderPay/orderPay?ordersn=${orderJson.ordersn}&status=2&tag=${orderJson.name}&api=${orderJson.api}`;
                wx.redirectTo({
                  url: url,
                });
                return;
              }
              
              wx.redirectTo({
                url: "../orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2",
              });
               
            } else {
              Toast(res.msg);
            }
            setTimeout(() => {
              that.setData({
                clicktag: 0,
                addressCodeClick:0
              });
            }, 1000);
          },
          fail: (res) => {
            console.log(res);
          },
        });
      }
    }
  },
  isHasInstall() {
    //判断是否有勾选了上门安装服务
    for (let j = 0; j < this.data.goodsInfo.service_fee_items.length; j++) {
      if (this.data.goodsInfo.service_fee_items[j].code == "liveInstall") {
        return true;
      }
    }
    return false;
  },
  inpCpsTxt(e) {
    let txt = e.detail.value;
    this.setData({
      cpsTxt: txt,
    });
  },

  //组装商品信息
  _assembleGoods() {
    let newGoods = [];
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      for (let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++) {
        let model = {};
        model.goods_id = this.data.goodsInfo.orders[j].order_goods[i].goods_id;
        model.total = this.data.goodsInfo.orders[j].order_goods[i].total;
        model.option_id = this.data.goodsInfo.orders[j].order_goods[i].goods_option_id;
        newGoods.push(model);
      }
    }
    return newGoods;
  },
  //组装json数据
  _assembleJson() {
    let json = {
      //公共数据
      address: encodeURIComponent(JSON.stringify(this.data.currentAddress)),
      goods: JSON.stringify(this._assembleGoods()),
      member_coupon_ids: JSON.stringify(this._assembleCoupons()),
      orders: JSON.stringify(this._assembleDeduction()),
      // 发票
      // invoice_type: this.data.invoice_list.invoice_type === "electron" ? 0 : 1,
      // rise_type: this.data.invoice_list.invoice_status === "person" ? 1 : 0,
      // call: this.data.invoice_list.call,
      // email: this.data.invoice_list.email,
      // company_number: this.data.invoice_list.company_number,
      //新的发票-发票插件
      invoice:this.data.invoice_list,
      mark: this.data.options.mark ? this.data.options.mark : 0,
      dispatch_type_id: this.data.selected, //配送方式 ，1：快递 ||2：门店自提||3：门店配送（送货上门）||8：自提点
      first_default: this.first_default || ''//是否首次请求，之后的请求都要回传这个参数。没有传这个参数的订单全部按默认首次请求处理
    };
    if (this.data.use_wechat_address && (this.data.selected == 1 || (this.data.selected == 0 && !this.data.use_wechat_address))) {
      // 只用于快递，并且开启了使用微信地址
      let usejson = {
        address: this.data.design_address || "",
        city: this.data.design_info.cityName,
        district: this.data.design_info.countyName,
        id: "",
        isdefault: "",
        latitude: "",
        longitude: "",
        mobile: this.data.design_info.telNumber,
        province: this.data.design_info.provinceName,
        street: "",
        uid: "",
        uniacid: "",
        username: this.data.design_info.userName,
        zipcode: "",
      };
      // 没有选择微信地址的时候，是整个adress都为空
      json.address = usejson.address?encodeURIComponent(JSON.stringify(usejson)):[];
    }
    // 分销活动页面购买的商品，带活动id
    if (this.data.activity_id) {
      json.activity_id = this.data.activity_id;
    }

    if (app.globalData.share_room_id) {
      json.share_room_id = app.globalData.share_room_id;
    }

    if (this.options.share_uid) {
      json.share_uid = this.options.share_uid;
    }

    if (this.data.hasGoodOpenDF) {
      //有商品开启自定义表单
      json.order_goods = this._assembleDiyForm();
    }
    if (this.data.show_recharge_mobile) {
      //有商品开启话费慢充
      json.order_goods = JSON.stringify(this.assembleGoodsTELData());
    }
    if (this.options.electricity == "electricity") {
      //有商品开启话费慢充
      json.order_goods = JSON.stringify(this.assembleGoodsTELData());
    }
    //油卡充值
    if(this.data.oil_account && this.data.oil_mobile){
      json.order_goods = JSON.stringify(this.assembleGoodsTELData());
    }

    if (this.data.cpstype == "1") {
      json.recharge_number = this.data.cpsTxt;
    }

    if (this.data.camilo_resources_coupon_type == 1) {
      // 直冲需要填写帐号
      json.recharge_number = this.data.recharge_number;
    }

    if(this.data.deliveryTimeParams.status == 1){
      json.delivery_day = this.data.shop_delivery_day;
      json.delivery_time = this.data.shop_delivery_time;
    }

    json = this.handleDataActionBuyUrl(json, "order");
    json = this.handleDataActionCartUrl(json, "order");

    if (this.data._root_tag == "store") {
      json.store_id = this.data.store_id;
      json.mobile = this.data.linkinfo.mobile;
      json.realname = this.data.linkinfo.name;
      json.cart_ids = JSON.stringify(this.data.storeCarts);

      let storeTable = this.data.storeTable||null;
      if(storeTable && storeTable.table_store == this.data.store_id) {
        json.table_id = storeTable.table_id;
      }
    } else if (this.data._root_tag == "rentCartBuy" || this.data._root_tag == "rentBuy") {
      let right = wx.getStorageSync("rentTimeRight") || "";
      let choose = wx.getStorageSync("rentTimeChoose") || "";
      let self = wx.getStorageSync("rentTimeSelf") || "";
      let lease_term = {};
      if (!app._isTextEmpty(choose)) {
        lease_term = choose;
      } else if (!app._isTextEmpty(self)) {
        lease_term = self;
      }

      json.lease_rights = app._isTextEmpty(right) == null ? [] : right;
      json.lease_term = lease_term;
      json.cart_ids = JSON.stringify(this.data._cart_ids);
    }

    if (this.data.selected == 2 || this.data.selected == 8 || this.data.selected == 12 || this.data.selected == 15) {
      json.mobile = this.data.linkinfo.mobile;
      json.realname = this.data.linkinfo.name;

      if (this.data._root_tag === 'o2oDeposit') {
        // 门店定金  后端需要把门店的地址给传过去 #86280
        this.data.currentAddId = 1; //地址没有id  写死一个
        let arr = this.data.store_info.store_address.split(' ');
        this._setAddressViewData({
          province: arr[0],
          city: arr[1],
          district: arr[2],
          street: arr[3],
          address: arr[4],
          mobile: this.data.store_info.store_mobile,
          username: this.data.store_info.store_name,
          address_id: 1
        });
        json.address = encodeURIComponent(JSON.stringify(this.data.currentAddress));
        // 设置地址界面
      }
    }

    if (this.data.selected == 8 || this.data.selected == 12) {
      json.package_deliver_id = this.data.selected == 8 ? this.data.defaultSelfCarry.id : this.data.o2oSelfCarry.id;
      delete json.address;
    }

    if (this.data.selected == 3) {
      json.mobile = this.data.store_info.store_mobile;
      json.realname = this.data.store_info.store_name;
    }
    if (this.data.selected == 10) {
      json.supplier_driver_distribution_address = this.data.supp_point;
    }

    Object.assign(json, this.data.orderLocationObj);
    return json;
  },

  //支付协议
  agreementPaybtn(e) {
    let agreeBol = e.detail;
    this.setData({
      agreementPay: agreeBol,
    });
  },
  showPay() {
    this.setData({
      agreementPayShow: true,
    });
  },
  showPayClose() {
    this.setData({
      agreementPayShow: false,
    });
  },
  diyFromEdit(e){
    this.setData({
      "diyform.form_id": e.detail.form_id,
      "diyform.pre_id": e.detail.preid,
    })
    if (this._findDiyForm(e.currentTarget.dataset.preid)) {
      let diyform_data_id = this._findDiyForm(e.currentTarget.dataset.preid);
      this.setData({
        "diyform.diyform_data_id": diyform_data_id,
      });
    }
    this.setData({
      diyShow: true,
      codeShow:false
    });
  },
  showDiy(e) {
    this.setData({
      "diyform.form_id": e.currentTarget.dataset.id,
      "diyform.pre_id": e.currentTarget.dataset.preid,
    });
    if (this._findDiyForm(e.currentTarget.dataset.preid)) {
      let diyform_data_id = this._findDiyForm(e.currentTarget.dataset.preid);
      this.setData({
        "diyform.diyform_data_id": diyform_data_id,
      });
    }
    this.setData({
      diyShow: true,
    });
  },
  showDiyClose() {
    this.setData({
      diyShow: false,
    });
  },
  traCheckedData(data) {
    this._setDiyForm(data.detail.pre_id, data.detail.diyform_data_id);
    this.showDiyClose();
  },
  getList(type) {
    let that = this;
    let _type = type;
    let urlStr = app.getNetAddresss("plugin.package-deliver.frontend.deliver.getList");
    if (_type == "o2o") {
      urlStr = app.getNetAddresss("plugin.package-deliver.frontend.store.deliver.getList");
    }
    let point = app.qqMapTransBMap(parseFloat(that.data.point.lng), parseFloat(that.data.point.lat));
    app._getNetWork({
      url: urlStr,
      data: {
        city_name: that.data.city,
        lat: point.lat,
        lng: point.lng,
        kwd: "",
        goods: JSON.stringify(this._assembleGoods()),
        store_id: this.data.options.store_id || 0,
        deliver_id: this.options.package_deliver_id|| ''
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (_type == "shop") {
            that.setData({
              deliverName:res.data.name,
              defaultSelfCarry: JSON.stringify(that.data.defaultSelfCarry) == "{}" ? res.data.list.data[0] : that.data.defaultSelfCarry,
            });
          } else if (_type == "o2o") {
            if (!this.data.o2oSelfCarry.id) {
              this.setData({
                o2odeliverName: res.data.name,
                o2oSelfCarry: res.data.list.data[0] ? res.data.list.data[0] : "" //没有就取第一个为默认自提点
              });
            }
          }
        } else {
          wx.showToast({
            icon: "none",
            title: "获取自提点失败",
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //获取经纬度
  getCurrentOrderLocation() {
    this._getLocation((mapdata, e) => {
      let orderLocationObj = {
        positioning_success: 1,
        province: mapdata.address_component.province,
        city: this.data.city
      };
      this.data.orderLocationObj = orderLocationObj;
    });
  },


  async checkAlbum(scopeName) {
    let writePhotosAlbum = await this.getAuthSetting(scopeName);
    return new Promise((resolve, reject) => {
      if (!writePhotosAlbum) {
        wx.showModal({
          title: "请开启授权",
          content: "是否跳转设置页开启授权",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[scopeName]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                },
              });
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      } else resolve(true);
    });
  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              },
            });
          } else resolve(true);
        },
        fail() {
          resolve(false);
        },
      });
    });
  },
  toO2oSearchDiyBtn() {
    //门店搜索插件 自定义下单页按钮
    try {
      wx.redirectTo({
        url: this.data.storeSearchBtn.app_url,
      });
    } catch (e) {
      console.log(e);
    }
  },
  toFullPage() {
    // 跳转满额包邮页
    if (this.data._root_tag == this.data.TAG_ACTION_BUY) {
      //立即购买的，把他添加到购物车，从包邮页去结算变成购物车结算
      // 设置主要参数
      let urlStr = app.getNetAddresss("postageIncludedCategory.member-cart.store");
      app._postNetWork({
        url: urlStr,
        data: {
          goods_id: this.data._goodsId,
          total: this.data._total || 1,
          option_id: this.data._optionsId || 0
        },
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            let _cart_ids = [];
            _cart_ids.push(Number(res.data.cart_id));
            wx.navigateTo({
              url: '/packageE/orderullPackage/orderullPackage?cart_id=' + JSON.stringify(_cart_ids)
            });
          }
        },
        fail: (res) => {
          console.log(res);
        },
      });

    } else if (this.data._root_tag == this.data.TAG_ACTION_CART) {
      // 购物车下单 JSON.stringify(this.data._cart_ids)
      wx.navigateTo({
        url: '/packageE/orderullPackage/orderullPackage?cart_id=' + this.options.cart_ids
      });
    }
  },
  // 二开页面开发-胜天半子#79514
  onChange(e) {
    this.setData({
      sexSelect: e.detail
    });
  },
  cell_from_inp(e) {
    if (e.currentTarget.dataset.key == 'name') {
      this.setData({
        'design_info.userName': e.detail.value
      });
    }
    if (e.currentTarget.dataset.key == 'phone') {
      this.setData({
        'design_info.telNumber': e.detail.value
      });
    }
    if (e.currentTarget.dataset.key == 'adress') {
      this.setData({
        design_address: e.detail.value,
        'design_info.detailInfo': e.detail.value
      });
    }
    if(this.data.use_wechat_address && this.data.userAdress && this.data.design_address && (this.data.design_info.detailInfo || this.data.design_info.telNumber || this.data.design_info.userName)){
      //微信地址 开启 手动填完
      this._requestByAddress();
    }
  },
  tapShowArea() {
    this.setData({
      showArea: true
    });
  },
  onChangeVar(e){
    let {tag, status} = e.target.dataset||{};
    this.setData({
      [tag]: status
    })
  },
  onConfirmVar(e){
    console.log(e)
    this.onChangeVar(e);
    let {tag, status,name} = e.target.dataset||{};
    let detail = '';
    if(name == 'shop_delivery_day'){
      detail = (util.formatTime(new Date(e.detail))).slice(0,10);
    }
    if(name == 'shop_delivery_time'){
      detail = e.detail.value;
    }
    this.setData({
      [tag]: status,
      [name]: detail
    })
  },
  confirmArea(e) {
    this.setData({
      userAdress: `${e.detail[0].name} ${e.detail[1].name} ${e.detail[2].name}`,
      'design_info.provinceName': e.detail[0].name,
      'design_info.cityName': e.detail[1].name,
      'design_info.countyName': e.detail[2].name
    });
    this.checkWxAdress(this.data.design_info,true);
  },
  changeCityDeliveryCommunity(e) {
    this.setData({
      cityDelivery_community_id: e.detail
    });
  },
  setCityDeliveryCommunity() {
    let cityDelivery_community = this.data.cityDelivery.community_setting.community_list.find((item) => {
      return item.id == this.data.cityDelivery_community_id;
    });
    this.setData({
      cityDelivery_community,
      selectCommunityShow: false
    });
  },
  openCityDeliveryDay() {
    this.selectComponent(`.deliveryTime`).setPopShow();
  },
  cityDeliveryDayConfirm(evt) {
    this.setData({
      cityDelivery_deliveryTime: evt.detail
    });
    this.handleBuy();
  },
  getDistributionInfo(data=null){
    // 获取已有的自提点提货人、姓名信息记录
    //是否保存过自提点提货人和手机号信息，有的话自动填写【任务编号: 35632】
    let {mobile,realname} = data||{};//接口返回记录的数据
    let apiData = {'distributionUserMobile':mobile,'distributionUserName':realname};
    // 判断缓存对象是否为空
    let arr = Object.keys(wx.getStorageSync("selfCarryInfo"));
    let storageData = arr.length != 0?JSON.parse(wx.getStorageSync("selfCarryInfo")):{};//getStorageSync保存
    if(!this.data.linkinfo.name && !this.data.linkinfo.mobile){
      this.setData({
        "linkinfo.name": arr.length != 0 ? storageData.distributionUserName : (apiData.distributionUserName || ""),
        "linkinfo.mobile": arr.length != 0 ? storageData.distributionUserMobile : (apiData.distributionUserMobile || ""),
      });
    }
  },
});